关于css居中是前端面试中比较常问的问题之一,以下是我总结的关于css居中的一些方法。
第1种:margin:auto;
把margin设为auto,该方法只能对水平元素进行居中,对浮动元素或绝对定位元素无效。
第2种:text-align:center;
只对行内元素起作用,对块级元素无用。
只能对图片,按钮,文字等行内元素(display:inline或display:inline-block)的元素进行水平居中。
在IE6,IE7这两个浏览器下,对任何元素进行水平居中。
第3种:line-height
使用line-height让单行的文字垂直居中。
将文字的line-height设为文字父容器的高度,适用于只有一行文字的情况。
第4种:
利用css控制表格内容居中:text-align:center; vertical-align:middle
第5种:display:table-cell
对于不是表格的元素,通过display:table-cell将它模拟成一个表格单元格,然后利用表格的居中特性。
上述5种方法都是比较简单的居中方法,那么如何实现让一个div垂直居中?
html代码如下:
<div class="wrapper">
<div class="content"></div>
</div>
第一种:子元素相对父元素绝对定位水平垂直居中 margin:auto
.wrapper{
position:relative;
width:300px;
height:300px;
background:#ff0;
}
.content{
width:100px;
height:100px;
background:#f0f;
position:absolute;
left:0;
top:0;
bottom:0;
right:0;
margin:auto;
}
第二种:子元素相对父元素绝对定位水平垂直居中 margin负间距
.wrapper{
width:300px;
height:300px;
background:#ff0;
position:relative;
}
.content{
width:100px;
height:100px;
background:#f0f;
position:absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
注意:子元素进行绝对定位,top值和left值均设为50%,margin-top负值,设为子元素高度的50%,margin-left负值,设为子元素宽度的50%。
第三种:子元素相对父元素绝对定位水平垂直居中 transform变形
.wrapper{
width:300px;
height:300px;
background:#ff0;
position:relative;
}
.content{
width:100px;
height:100px;
background:#f0f;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
第四种:flex布局
.wrapper{
width:300px;
height:300px;
background:#ff0;
display:flex;
justify-content:center;
align-items:center;
}
.content{
width:100px;
height:100px;
background:#f0f;
}
justify-content:设置或检索弹性盒子元素在横轴方向上的对齐方式
align-items:设置或检索弹性盒子元素在侧轴方向上的对齐方式