在进行项目的布局中,我们会经常遇到居中的布局,不管是水平居中还是垂直居中,下面我们就总结下几种常见的布局方式:
DOM结构如下:
<div class="center1">
<div class="box">水平居中</div>
</div>
第一种:text-align: center;水平居中
这种方式居中用的最多的地方是文本居中,只对行内元素或者行内块元素有效,所以,当你定义父元素center1为text-align: center
时,只有box的文本会居中,而box本身是不居中的,要是box也居中,则需要把box变成行内元素(display:inline,会忽视宽高,只能文本撑开宽高)或者变成行内块元素(display:inline-block,不会忽视宽高):
.center1{
width:300px;
height:300px;
text-align: center;
border:1px solid orange;
}
.box{
width:100px;
height:100px;
/*margin:0 auto;*/
display: inline-block;
border:1px solid red;
}
第二种方式:相对定位与绝对定位方式垂直+水平居中
原理就是通过绝对定位定位父元素的50%位置,再通过margin回移自身宽高的一半即居中
.center1{
width:300px;
height:300px;
position:relative;
border:1px solid orange;
}
.box{
width:100px;
height:100px;
position: absolute;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
border:1px solid red;
}
第三种:margin水平居中
注意点就是:margin:0 auto只能水平居中,垂直方向设置auto无效,且自身一定要有固定宽度
.center1{
width:300px;
height:300px;
border:1px solid orange;
}
.box{
width:100px;
height:100px;
margin:0 auto;
border:1px solid red;
}
第四种:定位+margin的另类垂直+水平居中
.center1{
width:300px;
height:300px;
position:relative;
border:1px solid orange;
}
.box{
width:100px;
height:100px;
position: absolute;
left:0;
top:0;
bottom:0;
right:0;
margin:auto;
border:1px solid red;
}
第五种:flex弹性盒子垂直+水平居中
个人觉得,在布局方面,flex还是非常好用的,非常快速就可以搞定,唯一的缺点可能就是不兼容低版本的浏览器,特别是IE,
.center1{
width:300px;
height:300px;
// 变为弹性盒子
display: flex;
// 垂直水平居中
align-items:center;
justify-content: center;
border:1px solid orange;
}
.box{
border:1px solid red;
}
第六种:框架
当我们开发时可能会用到很多CSS库,每种css库都有自己的layout布局方式,比如elementui的layout布局 ,bootsrap的栅格系统,那他也有自己的居中方式,这也是比较快速的方式,可能限制会比较多一点