CSS:如何用img标签覆盖div(如背景图像)? [英] CSS: 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-position:center;
}
结果图片在div内居中并被调整大小, div的宽度或高度(取决于图像是否宽阔)。
现在我想用div中的image标签获得相同的结果。
< div>
< img src =images / img1.jpg/>
< / div>
有没有办法通过纯CSS来实现这一点?
使用 object-fit:cover
不会失去比例。
div {border:black solid;宽度:400px; height:400px;} img {width:100%;身高:100%; object-fit:cover}
< div> < img src =// lorempixel.com/100/100/>< / div>
注意:这是不是在IE中支持
As discussed here I am trying to get an image to be covered within a div. With just these simple lines I was able to achieve this via 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;
}
In result the image was centered within the div and was resized so it would fit the width or the height of the div (depending if the image was wide or not). Now I would like to achieve the same result with the image tag within the div.
<div>
<img src="images/img1.jpg"/>
</div>
Is there any way to get through this with plain CSS?
use object-fit:cover
to not lose ratio.
div {
border: black solid;
width: 400px;
height: 400px;
}
img {
width: 100%;
height: 100%;
object-fit: cover
}
<div>
<img src="//lorempixel.com/100/100" />
</div>
NOTE: this is not supported in IE
这篇关于CSS:如何用img标签覆盖div(如背景图像)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!