如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?


示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。


当前回答

最简单的方法是使用对象拟合:

<div class="container">
  <img src="path/to/image.jpg">
</div>

.container{
   height: 300px;
}

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

如果您使用Bootstrap,只需添加img响应类并更改为

.container img{
    object-fit: cover;
}

其他回答

此解决方案不会拉伸图像并填充整个容器,但会剪切部分图像。

HTML格式:

 <div><img src="/images/image.png"></div>

CSS:

div {
    width: 100%;
    height: 10em;
    overflow: hidden;

img {
    min-width: 100%;
    min-height: 100%;
}

这里有一个解决方案,即使提供的图像太小或太大,无法容纳div,它也可以在div中垂直和水平对齐img,而不进行任何拉伸。

HTML内容:

<div id="myDiv">
  <img alt="Client Logo" title="Client Logo" src="Imagelocation" />
</div>

CSS内容:

#myDiv
{
  height: 104px;
  width: 140px;
}
#myDiv img
{
  max-width: 100%;
  max-height: 100%;
  margin: auto;
  display: block;
}

jQuery部分:

var logoHeight = $('#myDiv img').height();
    if (logoHeight < 104) {
        var margintop = (104 - logoHeight) / 2;
        $('#myDiv img').css('margin-top', margintop);
    }

本文可能会帮助您:

.方形{位置:相对;宽度:300px;高度:300px;溢出:隐藏;}国际货币基金组织{位置:绝对;最大宽度:100%;宽度:100%;高度:自动;顶部:50%;左:50%;转换:转换(-50%,-50%);}img.景观{高度:100%;宽度:自动;}<div class=“square”><img src=“https://unsplash.it/400/500“alt=”图像“/></div><div class=“square”><img src=“https://unsplash.it/500/400“class=”landscape“alt=”图像“/></div>

简单的CSS解决方案:如何将不同尺寸的图像放在集合容器中(2017-05-01)

.方形{位置:相对;宽度:441px;高度:200px;溢出:隐藏;边框:1px实心黑色;}国际货币基金组织{最大宽度:100%;/*宽度:100%*/<----它拉伸图像并适合父对象高度:自动;/*转换:转换(-50%,-50%)*/<-----设置垂直和水平中心}img.景观{高度:100%;宽度:自动;}<div class=“square”><img src=“https://cdn.pixabay.com/photo/2020/08/28/12/32/man-5524488__340.jpg“alt=”图像“/></div>

我看到很多人都建议对象匹配,这是一个不错的选择。但是,如果您希望它也能在较旧的浏览器中工作,还有另一种方法可以轻松实现。

这很简单。我采用的方法是将图像放置在容器内,然后使用组合将其放置在中心:

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/

此逻辑适用于所有浏览器。

我以这种方式在超链接内水平和垂直居中并按比例缩放图像:

#link {
    border: 1px solid blue;
    display: table-cell;
    height: 100px;
    vertical-align: middle;
    width: 100px;
}
#link img {
    border: 1px solid red;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-height: 60px;
    max-width: 60px;
}

它在Internet Explorer、Firefox和Safari中进行了测试。

有关居中的更多信息,请参阅此处。