當圖片大於div時,想要圖片居中顯示,如果圖片等比例縮小可能會導致圖片不能填充整個div,如果直接將圖片不設置寬高,將其外層div設置overflow:hidden;這時即使外層div設置了水平垂直居中,圖片也不是居中的效果:
解決方法:
1- 把圖片設置為背景圖片
<div class="face-img-contain" id="face-img-back"> </div>
.face-img-contain{
width:348px;
height:436px;
margin:0 auto;
margin-top: 14px;
position: relative;
background-image: url(../images/face-img/test-22.png);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid gainsboro;
}
若是后台返回的地址,別忘了拼接方法正確
$("#face-img-back").css("background-image","url("+faceImg+")");
2- 給圖片設置相對div的100%的寬高,再設置object-fit:cover;
<div class="face-img-contain-new-new">
<img src="../images/face-img/test-22.png" alt="" class="face-img-defined1" id="face-img-photo">
</div>
.face-img-contain-new-new{
width:348px;
height:436px;
margin:0 auto;
margin-top: 14px;
position: relative;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
border: 1px solid gainsboro;
}
.face-img-defined1{
width:100%;
height:100%;
object-fit: cover;
}
。。。。。。
