闲来无事,被人问到如何使img在一个div中垂直居中显示,自己就总结了如下几种方法,供大家参考:
方法一:在box中添加span空元素
<div id="box">
<div class="img"></div>
<span></span>
</div>
#box{
width: 200px;
height: 200px;
background:black;
margin:0 auto;
text-align: center;
}
.img{
width: 100px;
height: 100px;
background:white;
display: inline-block;
vertical-align: middle;
}
#box span{
display: inline-block;
width:0;
height:100%;
vertical-align: middle;
}
方法二:使用定位法,使用定位法时,img包含两种情况:
(1)固定宽高
<div id="box">
<div class="img"></div>
</div>
#box{
width: 200px;
height: 200px;
background:black;
margin:0 auto;
text-align: center;
position: relative;
}
.img{
width: 100px;
height: 100px;
position: absolute;
background: white;
left:50%;
top:50%;
margin-top:-50px;
margin-left:-50px;
}
(2)无固定宽高
<div id="box">
<div class="img"></div>
</div>
#box{
width: 200px;
height: 200px;
background:black;
margin:0 auto;
text-align: center;
position: relative;
}
.img{
width: 100px;
height: 100px;
position: absolute;
background: white;
left:50%;
top:50%;
-webkit-transform: translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
方法三:设置父div为table-cell属性
<div id="box">
<div class="img"></div>
</div>
#box{
width: 200px;
height: 200px;
background:black;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.img{
width: 100px;
height:100px;
background: white;
display: inline-block;
}
方法四:使用flex布局
<div id="box">
<div class="img"></div>
</div>
#box{
width: 200px;
height: 200px;
background:black;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
margin:0 auto;
}
.img{
width: 100px;
height:100px;
background: white;
}
前两种是在开发中用的比较多的,最后一种在移动端布局使经常使用,只限子元素只有一个元素的情况下,以上为本人的见解,如有错误还请大家指正!