提问人:Yunes Ehsanpour 提问时间:10/17/2023 最后编辑:Yunes Ehsanpour 更新时间:10/17/2023 访问量:55
我的图像不适合其容器的整个高度 [复制]
my image doesn't fit the entire height of its container [duplicate]
问:
我的 div 元素中有一个图像,我希望我的图像适合其容器的整个高度,但这不会发生。我的形象是方形的。我不得不提一下,我不在乎纵横比。这是我的代码
我尝试了对象拟合属性,但没有帮助。
.container {
border-radius: 10px;
overflow: hidden;
width: 300px;
background-color: red;
}
.container img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
<div class='container'>
<img src="https://cdn140.picsart.com/39063465592866053138.webp?type=webp" alt="">
</div>
答:
0赞
mandy8055
10/17/2023
#1
设置容器的属性以获取获得的结果。这将使图像了解含义。height
100% height
.container {
border-radius: 10px;
overflow: hidden;
width: 300px;
height: 300px;
/* added this. You can adjust this as per your requirement */
background-color: red;
}
.container img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
<div class='container'>
<img src="https://cdn140.picsart.com/39063465592866053138.webp?type=webp" alt="">
</div>
如果您不想手动提供特定的高度,您可以做的另一件事是在容器上使用。像这样:flex
.container {
display: flex;
align-items: center;
border-radius: 10px;
overflow: hidden;
width: 300px;
background-color: red;
}
.container img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
<div class='container'>
<img src="https://cdn140.picsart.com/39063465592866053138.webp?type=webp" alt="">
</div>
编辑:
正如 @ralph.m 和 @Rene van der Lende 所指出的,您可以在图像上使用 display: block
或 vertical-align: bottom
,它们也可以以最少的努力为您完成工作。
评论
0赞
ralph.m
10/17/2023
这不是一个好的解决方案,而且完全没有必要。这只是有问题的图像的默认内联对齐方式。无需摆弄固定高度。
1赞
ralph.m
10/17/2023
对于这个特定问题来说,这有点矫枉过正。默认情况下,图像将与位于它们旁边的任何文本(如文本单词)的基线对齐。如果您不希望出现这种行为,最好只在图像上使用,或者将图像设置为或类似。将责任推给容器来解决图像本身的问题并不公平!display: inline
vertical-align: bottom
display: block
评论
img { display: block }
会做诀窍。默认情况下,图像会导致元素下方出现间隙。只是一件要记住的事情......display: inline
display: block
vertical-align: bottom