【问题标题】:Fit image to parent div's size使图像适合父 div 的大小
【发布时间】:2013-08-09 02:50:46
【问题描述】:

我做了一个div(div1),等于浏览器窗口大小。然后我在父 div (div1) 中创建了另一个 div (div2)。然后我在第二个 div (div2) 中放置了一个图像。我的浏览器窗口大小为 1360X638,图片大小为 1600*1200。

我希望图像根据父 div 的 (div1) 大小适合自己。所以图像(大于窗口大小)必须适合第二个 div(div2),它等于窗口大小),并且这个图像将完全适合 div 的大小(所以,没有任何滚动或裁剪显示中的图像)。

我已经搜索了一段时间。我找到的解决方案是将最大高度和宽度设置为 100%。我这样做了。

这部分是我写的:

<div style="max-width: 100%; max-height: 100%; background-color: red; margin-right: 0px; padding: 2 2 2 2; overflow:visible;">
    <div style="max-height: 100%; max-width: 100%;">
        <img style="max-width: 100%; max-height: 100%; overflow:visible;" src="1.jpg" />
    </div>
</div>

输出是这样的:

您可以看到右侧有一个滚动条。我不想在那里。

【问题讨论】:

  • 这看起来像一个 dup :stackoverflow.com/questions/4684304/…
  • @hendr1x,该链接没有任何可接受的答案。
  • 你检查过“背景尺寸:封面;”查看w3schools.com/cssref/…上的示例
  • 这里有一个根本问题。您的图像的纵横比可能与您的视口(浏览器窗口)纵横比不同。在某些情况下,如果视口比图像高,则需要使用 max-width,如果视口比图像宽,则需要使用 max-height。每当调整窗口大小时,您都需要一些 JavaScript/jQuery 来帮助您设置正确的样式。
  • @MarcAudet:谢谢!你的回答很有帮助。你解锁了一个新的观点。 :)

标签: html css


【解决方案1】:

jQuery 解决方案 - 概念证明

假设您有以下 HTML

<div class="container">
    <img src="http://placehold.it/1600x1200" />
</div>

您可以应用以下 CSS 规则来调整图像大小以适应视口(浏览器宽度或高度的 100%):

html, body {
    height: 100%;
    margin: 0;
}
.container {
    height: 100%;
    width: 100%;
    background-color: red;
    text-align: center; /* optional */
}
.container img {
    vertical-align: top;
}
.portrait img {
    width: 100%;
}

.landscape img {
    height: 100%;
}

使用以下 jQuery 方法根据视口的纵横比选择正确的 CSS 规则:

function resizeImg() {
    var thisImg= $('.container');
    var refH = thisImg.height();
    var refW = thisImg.width();
    var refRatio = refW/refH;

    var imgH = thisImg.children("img").height();
    var imgW = thisImg.children("img").width();

    if ( (imgW/imgH) > refRatio ) { 
        thisImg.addClass("portrait");
        thisImg.removeClass("landscape");
    } else {
        thisImg.addClass("landscape");
        thisImg.removeClass("portrait");
    }
}

$(document).ready(resizeImg())

$(window).resize(function(){
    resizeImg();
});

演示小提琴:http://jsfiddle.net/audetwebdesign/y2L3Q/

这可能不是完整的答案,但它可能是一个起点。

参考
我之前研究过一个相关问题,可能感兴趣:
Make image fill div completely without stretching

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 2015-05-06
    • 2013-12-21
    相关资源
    最近更新 更多