如何拉伸图片以填充< div>同时保持图像的纵横比? [英] How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?
问题描述
我需要将此图片延伸至可能的最大尺寸,而不会溢出它的< div>
或倾斜图片。
我无法预测图像的纵横比,因此无法知道是否使用:
< img src =urlstyle = width :100%;>
或
< img src =urlstyle = height :100%;>
我不能同时使用(即style =width: 100%; height:100%;),因为这会将图像拉伸以适合< div>
。
$ b
< div>
的大小由屏幕百分比设定,这也是不可预测的。 p>
更新2016年:
现代浏览器表现更好。所有你需要做的就是将图像宽度设置为100%( demo )
.container img {
width:100%;
}
由于您没有知道宽高比,你必须使用一些脚本。以下是我将如何使用jQuery( demo ):
CSS
.container {
width:40%;
身高:40%;
背景:#444;
margin:0 auto;
}
.container img.wide {
max-width:100%;
最大高度:100%;
height:auto;
}
.container img.tall {
最大高度:100%;
最大宽度:100%;
width:auto;
}
HTML
< div class =container>
< img src =http://i48.tinypic.com/wrltuc.jpg/>
< / div>
< br />
< br />
< div class =container>
< img src =http://i47.tinypic.com/i1bek8.jpg/>
< / div>
脚本
$(window).load(function(){
$('。container')。find('img')。each(function(){
var imgClass =(this。宽度/ this.height> 1)?'wide':'tall';
$(this).addClass(imgClass);
})
})
I need to make this image stretch to the maximum size possible without overflowing it's <div>
or skewing the image.
I can't predict the aspect-ratio of the image, so there's no way to know whether to use:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
I can't use both (i.e. style="width: 100%; height: 100%;") because that will stretch the image to fit the <div>
.
The <div>
has a size set by percentage of the screen, which is also unpredictable.
Update 2016:
Modern browser behave much better. All you should need to do is to set the image width to 100% (demo)
.container img {
width: 100%;
}
Since you don't know the aspect ratio, you'll have to use some scripting. Here is how I would do it with jQuery (demo):
CSS
.container {
width: 40%;
height: 40%;
background: #444;
margin: 0 auto;
}
.container img.wide {
max-width: 100%;
max-height: 100%;
height: auto;
}
.container img.tall {
max-height: 100%;
max-width: 100%;
width: auto;
}
HTML
<div class="container">
<img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>
<br />
<br />
<div class="container">
<img src="http://i47.tinypic.com/i1bek8.jpg" />
</div>
Script
$(window).load(function(){
$('.container').find('img').each(function(){
var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
$(this).addClass(imgClass);
})
})
这篇关于如何拉伸图片以填充< div>同时保持图像的纵横比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!