我需要使这张图像拉伸到最大尺寸,而不溢出它的<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>的大小由屏幕的百分比设置,这也是不可预测的。
当前回答
这对于HTML和CSS来说是不可能的,或者至少是非常奇特和复杂的。如果你愿意加入一些javascript,这里有一个使用jQuery的解决方案:
$(function() {
$(window).resize(function() {
var $i = $('img#image_to_resize');
var $c = $img.parent();
var i_ar = $i.width() / $i.height(), c_ar = $c.width() / $c.height();
$i.width(i_ar > c_ar ? $c.width() : $c.height() * (i_ar));
});
$(window).resize();
});
这将调整图像的大小,使其始终适合于父元素,不管它的大小如何。由于它被绑定到$(window).resize()事件,当用户调整窗口大小时,图像将会调整。
这并没有试图在容器中居中图像,这是可能的,但我猜这不是你想要的。
其他回答
有一个更简单的方法,只使用CSS和HTML:
HTML:
<div
class="fill"
style="background-image: url('path/to/image.jpg');">
</div>
CSS:
.fill {
background-size: cover;
background-position: center;
width: 100%;
height: 100%;
}
这将把你的图像作为背景,并拉伸它以适应div的大小而不失真。
使用这种方法,你可以在div中填充不同比例的div和图片。
jQuery:
$(window).load(function(){
$('body').find(.fillme).each(function(){
var fillmeval = $(this).width()/$(this).height();
var imgval = $this.children('img').width()/$this.children('img').height();
var imgClass;
if(imgval > fillmeval){
imgClass = "stretchy";
}else{
imgClass = "stretchx";
}
$(this).children('img').addClass(imgClass);
});
});
HTML:
<div class="fillme">
<img src="../images/myimg.jpg" />
</div>
CSS:
.fillme{
overflow:hidden;
}
.fillme img.stretchx{
height:auto;
width:100%;
}
.fillme img.stretchy{
height:100%;
width:auto;
}
我也有类似的问题。我只用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/
这种逻辑适用于所有浏览器。
要使此图像拉伸到最大可能的大小,而不会溢出或倾斜图像。
应用……
img {
object-fit: cover;
height: -webkit-fill-available;
}
图像的样式。
这不是一个完美的解决方案,但这个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%;
}