【问题标题】:Keep image aspect ratio when width exceeds height当宽度超过高度时保持图像纵横比
【发布时间】:2019-11-14 09:31:54
【问题描述】:

我试图在width > heightheight > width 时保持正确的图像纵横比。当宽度超过高度时,我遇到问题,图像将溢出到父容器中。我不希望这种情况发生,而是重新调整图像大小以保持正确的纵横比。

此示例的图像为 640 x 480,比例为 4:3

如果我拖动容器宽度小于高度,我什至需要填充顶部/底部而不会溢出图像。如果我将容器拖得比高度更宽,那么我什至需要向左/向右填充而不会使图像溢出。

.main {
    height: 100%;
    width: 100%;
}
.wrapper {
    position: relative;
    padding-bottom: 75%;
}
.wrapper img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

<div class="main">
    <div class="wrapper">
        <img src="https://placeimg.com/640/480/animals" />
    </div>
</div>

JSFiddle

【问题讨论】:

    标签: html css aspect-ratio


    【解决方案1】:

    对于现代浏览器,您应该只设置宽度。浏览器将执行其他所有操作。

    例子:

    .main {
        height: auto;
        width: auto;
    }
    .wrapper {
        position: relative;
        padding-bottom: 75%;
    }
    .wrapper img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
    }
    

    【讨论】:

    • 当你使主容器比高度宽时仍然存在问题。
    • 为了获得最佳响应,您应该使用引导程序。
    【解决方案2】:

    您可以设置height:autowidth:100% 以使您的图像具有响应性

    .my-img {
      width: 100%;
      height: auto;
    }
    &lt;img src="https://placeimg.com/640/480/animals" alt="Nature" class="my-img" &gt;

    【讨论】:

      猜你喜欢
      • 2015-08-27
      • 2021-02-09
      • 2014-07-01
      • 1970-01-01
      • 2013-02-26
      • 2013-07-07
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多