前言
最近刷前端面试题经常看到CSS水平垂直居中设置的题目,找了下相关方法试了下,总结了一些比较常用的。
这里统一设置父元素和定位子元素为
<div class="box">
<div id="content"></div>
</div>
.box{
width: 400px;
height: 400px;
background: #cae;
}
#content {
width: 300px;height: 300px;
background: #fc1;
}
(一)position方法
设置父元素相对定位,子元素绝对定位,利用子元素的绝对定位使子元素水平垂直居中,这种方法要知道元素的大小;
.box {
width: 400px;
height: 400px;
background: #cae;
position: relative;
}
#content {
width: 300px;height: 300px;
background: #fc1;
position: absolute;
top: 50px;left: 50px;
}
(二)position+margin方法
1.父元素相对定位,子元素绝对定位距离都设置为0,利用margin:auto;使子元素水平垂直居中.
.box2 {
width: 400px;
height: 400px;
background: #f1f;
position: relative;
}
#content2 {
width: 300px;height: 300px;
margin:auto;
background: #fc1;
position: absolute;
top: 0;left:0;bottom: 0;right: 0;
}
2.1.父元素相对定位,子元素绝对定位距离设置为50%(这里50%应该是父元素大小的50%),通过设置子元素大小的一半的负margin值使子元素水平垂直居中.
.box3{
width: 400px;
height: 400px;
background: #23f;
position: relative;
}
#content3 {
width: 300px;height: 300px;
background: #fc1;
position: absolute;
top: 50%;left: 50%;
margin-top: -150px;
margin-left: -150px;
}
(三)table-cell 方法
.box4{
width: 400px;
height: 400px;
background: #456;
display: table-cell;
text-align: center;
vertical-align: middle;
}
#content4 {
width: 300px;height: 300px;
background: #fc1;
display: inline-block;
}
(四)position+transform 方法
.box5{
width: 400px;
height: 400px;
background: #789;
position: relative;
}
#content5 {
width: 300px;height: 300px;
margin:auto;
background: #fc1;
position: absolute;
top: 50%;left: 50%;
-webkit-transform:translate(-50%,-50%);
transform:translate(-50%,-50%);
}
(五)flex 方法
1.利用弹性布局flex:设置align-items,justify-content都为center;
.box6{
width: 400px;
height: 400px;
background: #1f1;
display: flex;
align-items:center;
justify-content:center;
}
#content6 {
width: 300px;height: 300px;
background: #fc1;
}
2.弹性布局,子元素margin设置auto即可.
.box7{
width: 400px;
height: 400px;
background: #aaf;
display: flex;
}
#content7 {
width: 300px;height: 300px;
background: #fc1;
margin:auto;
}