在固定大小的div内显示未知大小的图像

6

我有一个固定大小的 <div>,例如 height:100pxwidth:100px

我必须在这个 <div> 中显示未知大小的图像,使以下情况出现:

  1. 图像宽度大于div宽度
  2. 图像宽度小于div宽度
  3. 图像宽度等于div宽度
  4. 图像高度大于div高度
  5. 图像高度小于div高度
  6. 图像高度等于div高度

无论如何,以下是最佳的跨浏览器策略,支持旧版浏览器,以满足以下标准:

  1. 图像周围没有白色空间
  2. 如果溢出,则水平和垂直居中

1
对我来说,在这种情况下最好的方法是使用background-images并进行居中对齐。否则,您需要一些js来找出图像是纵向还是横向,并利用width:100%height:auto或相反(height:100%width:auto)。 - otinanai
CSS的魔法等着你... - bjb568
2
Background-size:cover在寻求旧版浏览器支持时并不好用。我建议使用像Isotope或Masonry这样的js解决方案。 - Joe Conlin
4个回答

4
为了消除空白,将图片的min-heightmin-width都设置为100%。要裁剪溢出内容,请在div上设置overflow: hidden。要居中溢出的图片,请使用绝对定位和一些JavaScript根据图片的大小设置topleft值。 编辑:如果图像在两个维度上都大于容器,请使用一些JavaScript删除minHeightminWidth,然后将height设置为100%。如果这样会在宽度上留下空白,请将height设置为"",将width设置为100%
.centeredImageContainer {
    height: 100px;
    width: 100px;
    overflow: hidden;
    position: relative;
}
.centeredImage {
    min-width: 100%;
    min-height: 100%;
    position: absolute;
}

function centerImage(img) {
    var container = img.parentNode;
    if (img.offsetHeight > container.clientHeight &&
        img.offsetWidth > container.clientWidth) {
        img.style.minHeight = "0";
        img.style.minWidth = "0";
        img.style.height = "100%";
        if (img.offsetWidth < container.clientWidth) {
            img.style.height = "";
            img.style.width = "100%";
        }
    }
    img.style.top = ((container.offsetHeight - img.offsetHeight) / 2) + "px";
    img.style.left = ((container.offsetWidth - img.offsetWidth) / 2) + "px";
}

jsfiddle.net/QRU4w/2


一些数学家可能可以给你一个公式来确定是否需要为超大图片设置高度或宽度,这样的公式甚至可能比我的愚蠢算法更优雅。但是,我怀疑这不会对性能或可读性产生太大影响。显然,如果容器保证是正方形,那么公式将是简单的,但我有印象它可能并不总是正方形。 - gilly3
感谢您抽出时间。 - timmaktu

3

编辑:

演示代码

HTML:
<div id="myPic"></div>

CSS,如果您想要将大图片缩小以适应整个div,同时又想让小图片扩展以填充整个div:

#myPic{ 
  width: 100px;
  height: 100px;
  background-image: url(/abs/path/img.jpg);
  background-size: cover;
}

如果你想让一个大图片只显示中间的一部分而不改变大小,可以使用CSS:

#myPic{ 
  width: 100px;
  height: 100px;
  background-image: url(/abs/path/img.jpg);
  background-position: center center;
}

我不知道同时使小图片扩展适应,而不缩小大图片的方法。

0

如果您的意思是需要在横向图片上方没有空白,例如(即使照片原本不是正方形也需要填充正方形),那么您可以考虑将图像设置为div的背景,并使用background-size: cover。请参见this link以获取浏览器支持信息。


background-size: cover在旧版浏览器中不具备跨浏览器支持。 - timmaktu

0

最好的方法是使用object-fit属性。

.image-container {
    width: 400px;
    height: 300px;
}

.centered-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
<div class="image-container">
  <img src="https://24seven.co.ke/uploads/sliders/1550944223ecommmerce.jpg" alt="24seven Developers slider" class="centered-image">
</div>

如需更多示例和极客内容,请参见this


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接