css - 在不设置尺寸的情况下在 CSS 中裁剪图像

标签 css sass

我知道 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/

相关文章:

php - 突出显示 Div 标签下的文本

html - CSS 在悬停在网页链接(<a> 标签)上时调整背景颜色的高度

javascript - 输入字段收到文本时如何更改标签颜色?

css - Normalize.css 不起作用 Angular 4/5

css - Sublime Text CSS 奇数对象语法突出显示 - 插件存在吗?

html - Bootstrap - 具有相同结构的导航栏和页脚

html - 表格内每个 tbody 的垂直条

javascript - Webpack 错误 : You may need an appropriate loader to handle this file type. | @字符集 "UTF-8";

javascript - Bootstrap-sass gem Javascript 不能在 Rails 4 中工作

javascript - Carousel slider - 如何流畅地制作卡片动画?