我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。

我无法预测图像的纵横比,所以没有办法知道是否使用:

<img src="url" style="width: 100%;">

or

<img src="url" style="height: 100%;">

我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。

<div>的大小由屏幕的百分比设置,这也是不可预测的。


当前回答

如果你想设置一个最大宽度或高度(这样它就不会很大),同时保持图像的纵横比,你可以这样做:

img{
   object-fit: contain;
   max-height: 70px;
}

其他回答

要使此图像拉伸到最大可能的大小,而不会溢出或倾斜图像。

应用……

img {
  object-fit: cover;
  height: -webkit-fill-available;
}

图像的样式。

我在寻找一个类似的问题时遇到了这个问题。我正在制作一个响应式设计的网页,页面上放置的元素的宽度设置为屏幕宽度的百分比。高度用vw值设置。

因为我用PHP和数据库后端添加了帖子,纯CSS是不可能的。然而,我确实发现jQuery/javascript的解决方案有点麻烦,所以我想出了一个整洁的解决方案(至少我是这么认为的)。

HTML (php)

div.imgfill { float: left; position: relative; background-repeat: no-repeat; background-position: 50% 50%; background-size: cover; width: 33.333%; height: 18vw; border: 1px solid black; /*frame of the image*/ margin: -1px; } <div class="imgfill" style="background-image:url(source/image.jpg);"> This might be some info </div> <div class="imgfill" style="background-image:url(source/image2.jpg);"> This might be some info </div> <div class="imgfill" style="background-image:url(source/image3.jpg);"> This might be some info </div>

通过使用style="",可以让PHP动态更新我的页面,css样式和style=""将最终在一个完美覆盖的图像中结束,缩放以覆盖动态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()事件,当用户调整窗口大小时,图像将会调整。

这并没有试图在容器中居中图像,这是可能的,但我猜这不是你想要的。

2016年更新:

现代浏览器的表现要好得多。你所需要做的就是将图像宽度设置为100%(演示)

.container img {
   width: 100%;
}

由于您不知道纵横比,因此必须使用一些脚本。下面是我如何用jQuery(演示)做到这一点:

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>

脚本

$(window).load(function(){
 $('.container').find('img').each(function(){
  var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
  $(this).addClass(imgClass);
 })
})

如果你能够将图像设置为背景图像,那么你可以这样做,这将裁剪图像而不拉伸它:

<div style="background-image: url(...); background-size: cover; width: 100%; height: 100%;"></div>

如果你需要坚持使用<img>标签,那么从2019年开始,你现在可以使用对象适合css属性,它接受以下值: 填充|包含|覆盖|无|缩小

参见https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

举个例子,你可以有一个存放图像的容器:

<div class="container">
    <img src="" class="container_img" />
</div>

.container {
    height: 50px;
    width: 50%;
}

.container_img {
    height: 100%;
    width: 100%;
    object-fit: cover;
}