为什么我的图像高度缩放不正确?

Why isn't my image height scaling correctly?

所以我正在制作一个图片显示在 200x200 像素列表项中的图库

#gallery-list-ui li {
    display: block;
    margin: 10px;
    height: 200px;
    width: 200px;
    overflow: hidden;
}

为了让纵向/横向图像使用整个 height/width,我使用 javascript 来决定是否应该将高度或宽度设置为 100%。

var portrait    = ($img.height() > $img.width() ? true : false);

if(portrait){
    $img.css({'width' :'100%', 'height' : 'auto'});
} else {
    $img.css({'height' :'100%', 'width' : 'auto'});
}

结果是肖像图像正确缩放

<img src="img.jpg" style="width: 100%; height: auto;">

但横向图像缩放其原始高度的 100%,并且不限于列表框的高度。

<img src="img.jpg" style="height: 100%; width: auto;">

我在这里错过了什么?谁能解释为什么会这样? 在这里查看我的 fiddle:https://jsfiddle.net/smyhbckx/5/

尝试在图像上使用 object-fit:cover;height:100% 属性 并向容器添加以下样式

.img-container {
    width: 200px;
    height: 200px;
}

希望这能解决您的问题

https://jsfiddle.net/smyhbckx/7/

为 .img-container 添加高度:

.img-container{
    height: 100%;
}

CSS身高要求很严格。它基于元素的直接父级的高度。 img 的直接父级是 .img-container - 它没有高度(意思是 height: auto;)。解析器将其识别为未知数字,因此您的 img 高度未缩放。