我有一个包含许多页面和不同背景图片的网站,我使用 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/