假定外层的高度和宽度已经固定,通用的HTML和CSS代码:
Html:
<div class="img">
<img src="http://dummyimage.com/200x200/f66/"/>
</div>
Style:
.img {
300px;
height:300px;
margin:20px auto;
background:#00f;
}
####相对定位+margin:auto
利用图片相对于外层浮动,加上margin:auto.
<div class="img img1">
<img src="http://dummyimage.com/200x200/f66/"/>
</div>
.img1 {
position:relative;
}
.img1 img {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
####flexbox
利用flexbox里面的垂直居中属性:align-items:center(垂直居中)和justify-content:center(水平居中);
<div class="img img2">
<img src="http://dummyimage.com/200x200/f66/"/>
</div>
.img2 {
display:-webkit-box;
display:-ms-flexbox;
display:flex-box;
display:flex;
-webkit-box-align:center;
-ms-flex-align:center;
align-items:center;
-webkit-box-pack:center;
-ms-flex-pack:center;
justify-content:center;
text-align:center;
}
####table-cell
利用display:table-cell+图片vertical-align:middle
<div class="img img3">
<span class="icenter"><img src="http://dummyimage.com/200x200/f66/"/></span>
</div>
.img3 .icenter {
display:table-cell;
vertical-align:middle;
text-align:center;
height:300px;
300px
}
.img3 img {
vertical-align:middle;
display:inline-block
}
####增加一个空白标签
<div class="img img4">
<img src="http://dummyimage.com/200x200/f66/"/>
<i class="iblock"></i>
</div>
.img4 {
text-align:center
}
.img4 img {
vertical-align:middle
}
.img4 .iblock {
display:inline-block;
height:100%;
0;
vertical-align:middle
}