正如这里所讨论的,我试图让一个图像被覆盖在一个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="//loremflickr.com/100/100" />
</div>
注意:IE 不支持此功能
<小时 />它在IE中不起作用(顺便说一下,它是一个过时的浏览器,所以请教育您的客户至少使用升级的浏览器EDGE(,但是有一些object-fit
的polyfill可以使object-fit
工作。
以下是一些示例:
- 对象适合图像
- Constancecchen/object-fit-pollyfill
- CSS对象适合属性的填充代码
或者,如果您认为仅对该属性使用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' />
如果要在不使用 CSS 背景图像的情况下重新创建background-size: cover;
外观,可以使用以下命令来实现所需的结果。但是请记住,始终需要一个容器来保存图像。
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 指定了大小。