子元素在父元素居中的常用方法-CSS

在前端开发中,经常会遇到子元素需要在父元素居中的情况,而对应的css方法也是多种多样的。子元素在父元素的居中问题也是在面试中经常被问到的问题,本文总结了在日常开发中最经常用到的几种方法,供大家参考。

1、未知元素大小

  • 1.1 子绝父相布局,top、right、bottom、left都设为0,margin属性设为auto
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin: auto;
    width:200px;
    height:200px;
    background-color:red;
}
  • 1.2 子绝父相布局
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:200px;
    height:200px;
    background-color:red;
}
  • 1.3 使用flex布局
#father{
    display:flex;
    flex-direction:row;
    justify-content:center;
    align-items:center;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    width:200px;
    height:200px;
    background-color:red;
}

2、已知元素大小

  • 2.1 子绝父相布局,top和left设置50%,margin-left设置子元素一半宽度的相反数,margin-top设置子元素高度一半的相反数
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-100px;
    margin-left:-100px;
    width:200px;
    height:200px;
    background-color:red;
}
  • 2.2 直接计算出来,margin-top设置为(父元素高度-子元素高度)/2,margin-left设置为(父元素宽度-子元素宽度)/2
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    margin-top:100px;
    margin-left:100px;
    width:200px;
    height:200px;
    background-color:red;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容