- 方案一:vertical-align
注意:vertical-align 生效的前提是元素的 display:inline-block,并且在使用 vertical-align:middle 的时候需要一个兄弟元素做参照物,让它垂直于兄弟元
素的中心点
vertical-align 对齐的方法是寻找兄弟元素中最高的元素作为参考
<!--html-->
<div class="box">
<div class="item"></div>
<div class="emp"></div>
</div>/*css*/
.box{
width:600px;height:500px;background-color:red;
text-align:center;display:inline-block
}
.item{
width:400px;height:200px;background-color:orange;
display:inline-block;vertical-align:middle
}
.emp{
display:inline-block;height:100%;vertical-align:middle
}- 方案二::before,基于方案一的改进(无缘无故多一个 emp 占位元素总是不好的)
<!--html-->
<div class="box">
<div class="item"></div>
</div>/*css*/
.box{
width:600px;height:500px;background-color:red;
text-align:center;display:inline-block
}
.box:before{
content: '';display:inline-block;height:100%;vertical-align:middle
}
.item{
width:400px;height:200px;background-color:orange;
display:inline-block;vertical-align:middle
}- 方案三:绝对定位
<!--html-->
<div class="box">
<div class="item"></div>
</div>/*css*/
.box{
width:600px;height:500px;background-color:red;
position: relative;
}
.item{
width:400px;height:200px;background-color:orange;
position: absolute;top: 50%;left: 50%;
/*以下 2 种方式任选一个:*/
margin-left: -200px;margin-top: -100px;
/* or */
transform: translateX(-50%) translateY(-50%);
}- 方案四:弹性盒,推荐方案
<!--html-->
<div class="box">
<div class="item"></div>
</div>/*css*/
.box{
width:600px;height:500px;background-color:red;
display: flex;justify-content: center;align-items: center;
}
.item{
width:400px;height:200px;background-color:orange;
}
坏蛋格鲁