因此,我前段时间也提出了一个类似的问题,即img如何适合div,答案是设置图像的height: 100%
和width: 100%
,效果很好。但是现在我还在该div中使用了flexbox
,并且img仍然在底部溢出...
.d1 {
background: green;
width: 300px;
height: 100px;
padding: 5px;
}
.d2 {
background: red;
display: flex;
padding: 5px;
}
.img1 {
width: 100%;
height: 100%;
}
<div class="d1">
<div class="d2">
<img class="img1" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Cityoflondon2019june.jpg">
</div>
</div>
答案 0 :(得分:1)
将height:100%
赋予图片的父div。也可以调整填充或使用calc
设置高度height:calc(100% - 10px)
,请参见下文。
.d1 {
background: green;
width: 300px;
height: 100px;
padding: 5px;
}
.d2 {
background: red;
display: flex;
padding: 5px;
height: calc(100% - 10px);
}
.img1 {
width: 100%;
height: 100%;
}
<div class="d1">
<div class="d2">
<img class="img1" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Cityoflondon2019june.jpg">
</div>
</div>
希望这会有所帮助:)
答案 1 :(得分:1)
基本上,您需要将高度添加到img容器中,并将object-fit:cover属性添加到img中,还需要从img中移除高度。 PS:适合物体会保持图像的长宽比。
<!DOCTYPE html>
<html>
<head>
<style>
.d1 {
background: green;
width: 300px;
height: 100px;
padding: 5px;
}
.d2 {
background: red;
display: flex;
padding: 5px;
height: calc(100% - 10px); // minus padding
}
.img1 {
width: 100%;
object-fit: cover; //not supported in IE
}
</style>
</head>
<body>
<div class="d1">
<div class="d2">
<img class="img1" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Cityoflondon2019june.jpg">
</div>
</div>
</body>
</html>
答案 2 :(得分:0)
.d1 {
display: flex;
flex-wrap: nowrap;
background: green;
width: 300px;
height: 100px;
}
.d2 {
background: red;
display: flex;
padding: 5px;
}
.img1 {
width: 100%;
height: 100%;
}
<div class="d1">
<div class="d2">
<img class="img1" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Cityoflondon2019june.jpg">
</div>
</div>
答案 3 :(得分:0)
将高度和宽度从.d1
移至.d2
。
.d2 {
width: 300px;
height: 100px;
}