gpt4 book ai didi

html - 使图像适合父 div 的大小

转载 作者:行者123 更新时间:2023-11-28 08:05:08 25 4
gpt4 key购买 nike

我做了一个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>

输出是这样的:

Enter image description here

可以看到右侧有一个卷轴。我不想在那里。

最佳答案

jQuery 解决方案 - 概念验证

假设您有以下 HTML:

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

您可以应用以下 CSS 规则来调整图像大小以适合视口(viewport)(浏览器宽度或高度的 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 方法根据视口(viewport)的纵横比选择正确的 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();
});

演示 fiddle :http://jsfiddle.net/audetwebdesign/y2L3Q/

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

引用
我之前处理过一个相关的问题,可能感兴趣:
Make image fill div completely without stretching

关于html - 使图像适合父 div 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29527893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com