我创建了一个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>
Run Code Online (Sandbox Code Playgroud)
输出是这样的:

您可以看到右侧有一个滚动条.我不希望那里.
假设您有以下HTML:
<div class="container">
<img src="http://placehold.it/1600x1200" />
</div>
Run Code Online (Sandbox Code Playgroud)
您可以应用以下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%;
}
Run Code Online (Sandbox Code Playgroud)
使用以下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();
});
Run Code Online (Sandbox Code Playgroud)
演示小提琴:http://jsfiddle.net/audetwebdesign/y2L3Q/
这可能不是完整的答案,但它可能是一个开始的地方.
参考
我之前研究过一个相关的问题,这可能是有意义的:
使图像填充div完全没有拉伸