(1)使用background-position属性
<div className='bgImg'><div/>.bgImg {background:url('./***.png');width: 100%;height: 0;padding-bottom: 42%;background-repeat: no-repeat;background-size: cover;border-radius: 5px 5px 0px 0px;background-position : center;}
(2)使用 object-fit属性
img{display: block;width:100%;height: 6.917rem;object-fit: cover;}//该方法是使用object-fit属性裁剪图片,但是保持图片的原始比例,避免了图片变形。
(3)弹性盒子
对于宽高比固定的图片来说,可以设置固定的宽高使用弹性盒子居中显示。
div{width:200px;height:400px;display:flex;justify-content: center;align-items: center;img{width:300px;height:600px;}}
(4)定位
div{width:200px;height:400px;position:relative;img{width:300px;height:600px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);}}
(5)onLoad事件
<!--长图片--><div class="banner"><img src={hImg} alt=""onLoad={this.toCenterImage}></div><!--宽图片--><div class="banner"><img src={wImg} alt=""onLoad={this.toCenterImage}></div>//jstoCenterImage=(e) => {let heightScorll, widthScorll,img = e.currentTarget, //图片节点width = img.naturalWidth, //图片宽height = img.naturalHeight, //图片高parentNode = img.parentNode, //父元素节点parentWidth = parent.offsetWidth, //父元素宽parentHeigth = parent.offsetHeight; //父元素高//判断是长图片还是宽图片来给图片宽高赋值,长图设置宽固定,高度自适应;宽图设置固定高,宽度自适应。width >= height ? (heightScorll = height >= parentHeigth ? '100%' : height+'px', widthScorll = 'auto') : (heightScorll = 'auto', widthScorll = width >= parentWidth ? '100%' : width+'px');//修改图片宽高img.style.height = heightScorllimg.style.width = widthScorll}
