使用CSS控制图片显示居中的两种方式
示例图片
一、使用img标签显示
原理是在固定在容器中,让不同纵横比的图片垂直或水平居中
html代码
<div class="img-box">
<img src="http://7xw2i7.com1.z0.glb.clouddn.com/tmp8B06.tmp.jpg" alt="image show"/>
</div>
<div class="img-box">
<img src="http://7xw2i7.com1.z0.glb.clouddn.com/tmpB2E5.tmp.png" alt="image show"/>
</div>
css代码
.img-box {
width: 200px;
height: 200px;
text-align: center;
}
.img-box img {
max-width: 100%;
max-height: 100%;
margin-top: 50%;
transform: translateY(-50%);
}
二、使用背景方式显示
原理是先将图片做作为容器的背景,设置背景为不重复,全部包含,居中
另外可以将background-size的值设置为cover可以充满容器,自适应长宽比例,多出的部分会裁去
.img-box {
width: 200px;
height: 200px;
background-image: url("http://7xw2i7.com1.z0.glb.clouddn.com/tmpB2E5.tmp.png");
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}