1.高度不固定-单个元素垂直居中
<div class="box">
<div class="content">高度不固定</div>
</div>
.box{
background: #f0f0f0;
height: 400px;
position: relative;
}
/*缺点:要用到 transform ,兼容性较差(不太准确)*/
.content{
background: #0fbdce;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
方法二:
.box{
background: #f0f0f0;
height: 400px;
display: table-cell;
vertical-align: middle;
}
.content{
background: #0fbdce;
}
2.宽度不固定--单个元素水平居中
<div class="box">
<div class="content">宽度不固定</div>
</div>
.box{
background: #b0b0b0;
height: 100%;
}
/*缺点:设置为表格元素,内部元素的布局有可能收到影响*/
.content{
display: table;
margin: 0 auto;
background: #00009b;
color: white;
}
方法二:
.box{
background: #b0b0b0;
height: 100%;
position: relative;
}
/*缺点:要用到 transform ,兼容性较差*/
.content{
position: absolute;
left: 50%;
transform: translateX(-50%);
background: #00009b;
color: white;
}