【问题标题】:Height 100% if tall, width 100% if wide高 100% 高,宽 100% 宽
【发布时间】:2020-07-12 18:16:21
【问题描述】:

我的 img 生成随机大小的随机图像,有时高有时宽。如何使 img 永远不会大于或小于父容器?高 100% 高,宽 100% 宽。

.image-container{
width: 75rem;
height: 50rem;
}

/**this does not work**/
img{
    max-width:100%;
    max-height:100%;
}

【问题讨论】:

  • 你试过 img{ width: 75rem;高度:50rem; }
  • 改用widthimg{ width: 100%; height: 100%; }
  • 工作正常,肯定还有别的。

标签: html css


【解决方案1】:

在您决定将高度或宽度设为 100% 之前,您需要一些 JavaScript 来检查图像的比例(如果它们是横向或纵向)。

window.onload = function() {
    let images = document.querySelectorAll("img");
    for ( let i = 0; i < images.length; i++ ) {
        images[i].width <= images[i].height ? images[i].style.height = "100%" : images[i].style.width = "100%";
    }
}
.image-container {
    height: 300px;
    width: 500px;
    overflow: hidden;
    background: floralwhite;
    border: 2px solid silver;
    margin-bottom: 2em;
}
<div class="image-container">
    <img src="https://placehold.it/200x300">
</div>

<div class="image-container">
    <img src="https://placehold.it/600x300">
</div>

<div class="image-container">
    <img src="https://placehold.it/500x500">
</div>

【讨论】:

    猜你喜欢
    • 2016-08-09
    • 2015-02-04
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2013-11-09
    • 2013-12-06
    • 1970-01-01
    相关资源
    最近更新 更多