html - 是否有相当于背景大小 : cover and contain for image elements?

标签 html image css

我有一个包含许多页面和不同背景图片的网站,我使用 CSS 显示它们,例如:

body.page-8 {
    background: url("../img/pic.jpg") no-repeat scroll center top #000;
    background-size: cover;
}

但是,我想使用 <img> 在一个页面上显示不同的(全屏)图片元素,我希望它们具有与上述 background-image: cover; 相同的属性属性(图片不能从 CSS 中显示,它们必须从 HTML 文档中显示)。

我通常使用:

div.mydiv img {
    width: 100%;
}

或者:

div.mydiv img {
    width: auto;
}

使图片完整且响应迅速。但是,当屏幕太窄时,图片会缩小太多(width: 100%),并在底部屏幕中显示主体的背景色。另一种方法,width: auto; , 仅使图像全尺寸,不响应屏幕尺寸。

有没有办法以与 background-size: cover 相同的方式显示图像?有吗?

最佳答案

解决方案 #1 - object-fit property ( Lacks IE support )

只需在 img 上设置 object-fit:cover; 即可。

body {
  margin: 0;
}
img {
  display: block;
  width: 100vw;
  height: 100vh;
  object-fit: cover; /* or object-fit: contain; */
}
<img src="https://loremflickr.com/1500/1000" alt="A random image from Flickr" />

MDN - 关于object-fit:cover:

The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.

对于object-fit: contains:

The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box.

另见 this Codepen demo它将 object-fit:cover 应用于图像与 background-size:cover 应用于背景图像

进行比较

解决方案 #2 - 将 img 替换为带有 css 的背景图片

body {
  margin: 0;
}

img {
  position: fixed;
  width: 0;
  height: 0;
  padding: 50vh 50vw;
  background: url("https://loremflickr.com/1500/1000") no-repeat;
  background-size: cover;
}
<img src="https://via.placeholder.com/1500x1000" alt="A random image from Flickr" />

关于html - 是否有相当于背景大小 : cover and contain for image elements?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11670874/

相关文章:

html - 在最后一行调整 flex 元素的大小

image - 如何输出层叠图像或堆叠图像

html - 如何垂直对齐div的文本和图像中间?

python - 如何通过识别 Python 中的单条或多条水平线来分割图像?

javascript - this.call 不是函数

css - 如何在 native react 样式中设置动态值的 Prop

html - 在内部写入文本时,如何摆脱任何 html 标记(div、p、span)顶部和底部不需要的填充

javascript - jQuery 错误 - 将事件从 iframe 绑定(bind)到 parent.window

javascript - 点击表单提交后如何 "GO BACK"到上一页?

c++ - 在一个 QGraphicsView 中显示两个图像