我知道 object-fit: cover;
是在 css 中裁剪图像的好方法,但是否可以以相同的方式使用它,而不指定尺寸?而不是让它填充到父元素的宽度?
最佳答案
您也可以使用 object-fit: cover;
。只需确保为图像指定 width: 100%
和 height: 100%
即可。要使此解决方案起作用,父元素需要定义高度,否则图像将按原样显示。
<p>Parent element with no dimensions (default width to 100%): will maintain image aspect ratio (all image is visible).</p>
<div>
<img src="https://img.elo7.com.br/product/original/1B9A0FE/painel-1x0-70-bob-esponja-painel.jpg" style="object-fit: cover; width: 100%; height: 100%;">
</div>
<p>Parent element with specified dimensions: image will cover the area.</p>
<div style="width: 300px; height: 100px;">
<img src="https://img.elo7.com.br/product/original/1B9A0FE/painel-1x0-70-bob-esponja-painel.jpg" style="object-fit: cover; width: 100%; height: 100%;">
</div>
关于css - 在不设置尺寸的情况下在 CSS 中裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50163687/