搬运自stack overflow, 原答案链接 stackoverflow: Image height same as width
此方法适用于任何尺寸的图片,以width宽度为准,但是如果原尺寸比例不是正方形,显示出来的是按正方形比例截取的一部分。
CSS代码
.container {
position: relative;
width: 37%; /* 固定宽度 */
}
.container:after {
content: "";
display: block;
padding-bottom: 100%; /*padding取决于宽度,这里设置padding-bottom: 100%就可以得到正方形*/
}
.container img {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0; /*将图片大小固定为父类div的大小*/
width: 100%;
height: 100%;
object-fit: cover; /* 相当于 background-size: cover; of a background-image */
object-position: center;
}
HTML代码
<div class="container">
<img src="https://images.pexels.com/photos/1249588/pexels-photo-1249588.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"/>
</div>