[英]How to cover a div with an img tag (like background-image does)?
正如这里所讨论的,我试图让一个图像被一个 div 覆盖。 仅通过这些简单的线条,我就可以通过background-image
实现这一点:
div{
width: 172px;
height: 172px;
border-style: solid;
background-image: url('../images/img1.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
结果,图像在 div 内居中并调整大小,使其适合 div 的宽度或高度(取决于图像是否宽)。 现在我想用 div 中的图像标签实现相同的结果。
<div>
<img src="images/img1.jpg"/>
</div>
有什么办法可以用普通的 CSS 来解决这个问题吗?
使用object-fit:cover
不丢失比例。
div { border: black solid; width: 400px; height: 400px; } img { width: 100%; height: 100%; object-fit: cover }
<div> <img src="//lorempixel.com/100/100" /> </div>
注意:这在 IE 中不受支持
PS - 对于那些喜欢投票(并且正在投票)的人,只是因为“它在 IE 中不起作用” (顺便说一下,它是一个过时的浏览器,所以请教育您的客户至少使用升级的浏览器 EDGE),有一些object-fit
polyfills 可以使object-fit
工作。
这里有一些例子:
或者,如果您认为仅针对该属性使用 polyfill 是一种矫枉过正,这里是一个简单的片段,可以在 IE 中实现这一点。
您可以使用一个简单的 JS 代码段来检测是否支持object-fit
,然后将img
替换为svg
//for browsers which doesn't support object-fit (you can use babel to transpile to ES5) if ('objectFit' in document.documentElement.style === false) { document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('img[data-object-fit]').forEach(image => { (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}` image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E` }) }) }
img { display: inline-flex; width: 175px; height: 175px; margin-right: 10px; border: 1px solid red } /*for browsers which support object fit */ [data-object-fit='cover'] { object-fit: cover } [data-object-fit='contain'] { object-fit: contain }
<img data-object-fit='cover' src='//picsum.photos/1200/600' /> <img data-object-fit='contain' src='//picsum.photos/1200/600' /> <img src='//picsum.photos/1200/600' />
如果要重新创建background-size: cover;
在不使用 CSS 背景图像的情况下查看,您可以使用以下内容来达到预期的效果。 但是请记住,始终需要一个容器来保存图像。
div {
position: relative;
overflow: hidden;
}
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
min-width: 100%;
min-height: 100%;
height: auto;
width: auto;
}
根据您的附加 CSS,您可能需要使用max-width
和max-height
。
尝试这个:
div {
position:relative;
}
img {
max-height: 100%;
max-width: 100%;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
这假设您已为 div 指定了大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.