[英]Scaling Images Proportionally in CSS with Max-width
现在,我正在使用max-width来缩放图像以适应。 但是,它们并不按比例缩放。 有没有办法导致这种情况发生? 我对Javascript / jQuery持开放态度。
如果可能的话,有没有办法在不知道图像的原始尺寸的情况下做到这一点(可能使用Javascript / jQuery来确定)?
与接受的答案相反,您可以在不指定HTML大小的情况下执行此操作。 它可以在CSS中完成:
#content img {
max-width: 100px;
width: 100%;
height: auto;
}
您需要指定原始宽度和高度:
<img src="/whatever" width="100" height="200" alt="Whatever" />
然后在CSS中使用这样的东西:
#content img { max-width: 100%; height: auto }
你可以尝试使用jQuery,如果你没有前面的宽度和高度,但你的里程可能会有所不同:
$(function(){
$('#content img').load(function(){
var $img = $(this);
$img.attr('width', $img.width()).attr('height', $img.height());
});
});
显然,将#content
替换为您要将功能范围#content
的任何选择器。
设置恒定宽度时使用:
height: auto
以下是没有Javascript的方法。 将max-width
设置为所需的长度。
#content img {
max-width: 620px;
height: auto;
}
当我没有在img
标签中明确设置宽度或高度设置时,这适用于我使用Firefox 28,Chrome 34和Safari 7在Mac上进行测试。
在一个人建议的max-width
设置之后,不要将CSS中max-width
设置为100%,因为任何比容器宽度窄的图像(如图标)都会比预期的要大得多。
使用图像上的宽度和最大宽度搞砸IE8。
将宽度放在图像上并将其包装在具有最大宽度的div中。 (然后诅咒MS。)
我必须满足以下要求:
我想出的最接近的是这个可怕的装置。 它需要三个元素和两个内联样式,但据我所知,这是按比例缩放图像的最佳方法。 所有height: auto;
这里的建议否定了在服务器端指定图像尺寸并导致内容在加载时跳转的观点。
.image {
position: relative;
}
.image img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<!-- container element with max-width prevents upscaling -->
<div class="image" style="max-width: 640px;">
<!-- div with padding equal to the image aspect ratio to make
the element the correct height -->
<div style="padding-top: 75%;"></div>
<!-- img scaled to completely fill container -->
<img src="//placebear.com/640/480" />
</div>
https://jsfiddle.net/Lqg1fgry/6/ - “Hello”就在那里你可以看到图像后面的内容是否会跳转。
希望它还为时不晚,但凭借这些代码,我设法在我的画廊中获得比例图像。 需要时间才能了解正在发生的事情,但要尝试并享受。
<style>
div_base {
width: 200px; // whatever size you want as constrain unchangeable
max-width: 95%; // this is connected to img and mus exist
}
div_base img {
width: auto !important; // very important part just have it there!
height: 95%; // and this one is linked to maxW above.
}
</style>
function resizeBackground() {
var scale=0;
var stageWidth=$(window).width();
var newWidth=$("#myPic").width();
var stageHeight=$(window).height();
var newHeight=$("#myPic").height();
if( $(window).width() > $(window).height() ) {
scale = stageHeight/newHeight;
scale = stageWidth/newWidth;
} else {
scale = stageWidth/newWidth;
scale = stageHeight/newHeight;
}
newWidth = newWidth*scale;
newHeight = newHeight*scale
$("#myPic").width(newWidth);
$("#myPic").height(newHeight);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.