一、css 实现图片在div中水平居中并且垂直居中?
以下的做法中假定外层的高度和宽度已经固定。通用HTML和CSS代码:
<div class="img"> <img src="http://dummyimage.com/200x200/f66/"/> </div>
.img { width:300px; height:300px; margin:20px auto; background:#00f; }
1.绝对定位+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; }
2.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; }
3.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; width:300px } .img3 img { vertical-align:middle; display:inline-block }
4.增加一个空白标签
兼容性较好,支持IE浏览器
<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%; width:0; vertical-align:middle }
转载请注明:谷谷点程序 » css 实现图片在div中水平居中并且垂直居中?