1. 宽高固定(绝对定位)
样式:
.box {
width: 300px;
height: 300px;
background-color: #eee;
position: relative;
}
.aaa {
width: 100px;
height: 100px;
background-color: #ccc;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
当然,也可以将margin-left: -50px; margin-top: -50px; 换成 transform: translate(-50%,-50%);
html:
<div class="box">
<div class="aaa"></div>
</div>
2. 宽高不固定(绝对定位)
.aaa {
background-color: #ccc;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
3. after伪类实现垂直居中对齐
样式:
#demo{
height:500px;
text-align:center;
width: 500px;
background-color: #eee;
}
#demo:after {
display: inline-block;
width:0;
height:100%;
vertical-align:middle;
content:'';
}
#demo p{
display:inline-block;
vertical-align:middle;
}
html:
<div id="demo">
<p>水平垂直居中的随意内容</p>
</div>
注意:after和before是指在内部内容的after和before,而不是在自身的前后。还有就是 vertical-align:middle;起作用是有条件的:inline,inline-block,table-cell 水平的元素上起作用。
4. flex
样式:
#demo{
height:500px;
width: 500px;
background-color: #eee;
display: flex;
justify-content: center; //控制flex-item在主轴上的展示方式
align-items: center; //控制flex-item在侧轴上的展示方式
}
#demo p {
background-color: #ccc;
}
html:
<div id="demo">
<p>水平垂直居中的随意内容</p>
</div>
5. display:table-cell
样式:
#demo {
height:500px;
width: 500px;
background-color: #eee;
display: table-cell;
vertical-align: middle;
}
#demo p {
width: 100px;
height: 100px;
margin: 0 auto;
background-color: #ccc;
}
html:
<div id="demo">
<p>水平垂直居中的随意内容</p>
</div>