我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。
我无法预测图像的纵横比,所以没有办法知道是否使用:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。
<div>的大小由屏幕的百分比设置,这也是不可预测的。
我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。
我无法预测图像的纵横比,所以没有办法知道是否使用:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。
<div>的大小由屏幕的百分比设置,这也是不可预测的。
当前回答
这招对我很管用
div img {
width: 100%;
min-height: 500px;
width: 100vw;
height: 100vh;
object-fit: cover;
}
其他回答
我也有类似的问题。我只用CSS解决了这个问题。
基本上,Object-fit: cover可以帮助你实现在div中定位图像时保持纵横比的任务。
但问题是物体匹配:封面在IE中无法工作,它采用100%的宽度和100%的高度,纵横比扭曲。换句话说,我在chrome浏览器中看到的图像缩放效果没有了。
我采用的方法是在容器中使用absolute定位图像,然后使用组合将其放在正中央:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
一旦它在中心,我给图像,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
这使得图像得到对象适合:覆盖的效果。
下面是上述逻辑的演示。
https://jsfiddle.net/furqan_694/s3xLe1gp/
这种逻辑适用于所有浏览器。
HTML:
<style>
#foo, #bar{
width: 50px; /* use any width or height */
height: 50px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">
JSFiddle
...如果你想设置或改变图像(以#foo为例):
jQuery:
$("#foo").css("background-image", "url('path/to/image.png')");
JavaScript:
document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";
这里发现的许多解决方案都有一些限制:一些不能在IE(对象适合)或旧浏览器中工作,其他解决方案不能缩放图像(只缩小它),许多解决方案不支持调整窗口大小,许多不是通用的,要么期望固定分辨率或布局(纵向或横向)
如果使用javascript和jquery不是一个问题,我有这个解决方案基于@Tatu Ulmanen的代码。我修复了一些问题,并添加了一些代码,以防图像是动态加载的,在开始时不可用。基本上,这个想法是有两个不同的css规则,并在需要时应用它们:一个是当限制是高度时,所以我们需要在两侧显示黑条,另一个是当限制是宽度时,所以我们需要在顶部/底部显示黑条。
function applyResizeCSS(){
var $i = $('img#imageToResize');
var $c = $i.parent();
var i_ar = Oriwidth / Oriheight, c_ar = $c.width() / $c.height();
if(i_ar > c_ar){
$i.css( "width","100%");
$i.css( "height","auto");
}else{
$i.css( "height","100%");
$i.css( "width","auto");
}
}
var Oriwidth,Oriheight;
$(function() {
$(window).resize(function() {
applyResizeCSS();
});
$("#slide").load(function(){
Oriwidth = this.width,
Oriheight = this.height;
applyResizeCSS();
});
$(window).resize();
});
对于像这样的HTML元素:
<img src="images/loading.gif" name="imageToResize" id="imageToResize"/>
设置外部容器div的宽度和高度。然后在img上使用下面的样式:
.container img{
width:100%;
height:auto;
max-height:100%;
}
这将帮助你保持你的img的纵横比
这不是一个完美的解决方案,但这个CSS可能会有所帮助。缩放是这段代码的工作原理,理论上,对于小图像,因子应该是无限大的,但在大多数情况下,2、4或8就可以了。
#myImage {
zoom: 2; //increase if you have very small images
display: block;
margin: auto;
height: auto;
max-height: 100%;
width: auto;
max-width: 100%;
}