(1)使用background-position属性

  1. <div className='bgImg'><div/>
  2. .bgImg {
  3. background:url('./***.png');
  4. width: 100%;
  5. height: 0;
  6. padding-bottom: 42%;
  7. background-repeat: no-repeat;
  8. background-size: cover;
  9. border-radius: 5px 5px 0px 0px;
  10. background-position : center;
  11. }

(2)使用 object-fit属性

  1. img{
  2. display: block;
  3. width:100%;
  4. height: 6.917rem;
  5. object-fit: cover;
  6. }
  7. //该方法是使用object-fit属性裁剪图片,但是保持图片的原始比例,避免了图片变形。

(3)弹性盒子

对于宽高比固定的图片来说,可以设置固定的宽高使用弹性盒子居中显示。

  1. div{
  2. width:200px;
  3. height:400px;
  4. display:flex;
  5. justify-content: center;
  6. align-items: center;
  7. img{
  8. width:300px;
  9. height:600px;
  10. }
  11. }

(4)定位

  1. div{
  2. width:200px;
  3. height:400px;
  4. positionrelative;
  5. img{
  6. width:300px;
  7. height:600px;
  8. position:absolute;
  9. top:50%;
  10. left:50%;
  11. transform:translate(-50%,-50%);
  12. }
  13. }

(5)onLoad事件

  1. <!--长图片-->
  2. <div class="banner">
  3. <img src={hImg} alt=""
  4. onLoad={this.toCenterImage}>
  5. </div>
  6. <!--宽图片-->
  7. <div class="banner">
  8. <img src={wImg} alt=""
  9. onLoad={this.toCenterImage}>
  10. </div>
  11. //js
  12. toCenterImage=(e) => {
  13. let heightScorll, widthScorll,
  14. img = e.currentTarget, //图片节点
  15. width = img.naturalWidth, //图片宽
  16. height = img.naturalHeight, //图片高
  17. parentNode = img.parentNode, //父元素节点
  18. parentWidth = parent.offsetWidth, //父元素宽
  19. parentHeigth = parent.offsetHeight; //父元素高
  20. //判断是长图片还是宽图片来给图片宽高赋值,长图设置宽固定,高度自适应;宽图设置固定高,宽度自适应。
  21. width >= height ? (heightScorll = height >= parentHeigth ? '100%' : height+'px', widthScorll = 'auto') : (heightScorll = 'auto', widthScorll = width >= parentWidth ? '100%' : width+'px');
  22. //修改图片宽高
  23. img.style.height = heightScorll
  24. img.style.width = widthScorll
  25. }