當圖片大於div時,想要圖片居中顯示,若是圖片等比例縮小可能會致使圖片不能填充整個div,若是直接將圖片不設置寬高,將其外層div設置overflow:hidden;這時即便外層div設置了水平垂直居中,圖片也不是居中的效果:javascript
解決方法:css
1- 把圖片設置爲背景圖片java
<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;flex
<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; }
。。。。。。url