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

时间:2014-01-21 17:30:23

标签: javascript html css

我的<div>固定大小为height:100p x和width:100px。 我必须在<div>内显示未知大小的图像,以便出现以下情况:

  1. 图像宽度&gt; div width
  2. 图像宽度&lt; div width
  3. 图片宽度= div宽度
  4. 图像高度&gt; div height
  5. 图像高度&lt; div height
  6. 图像高度= div高度
  7. 无论如何,最好的跨浏览器策略是什么,支持旧版浏览器,以下列标准显示它们:

    1. 图片周围没有空白区域
    2. 如果溢出
    3. ,很好地居中(水平和垂直)

4 个答案:

答案 0 :(得分:4)

要消除空白区域,请为图片设置min-heightmin-width100%。要剪切溢出,请在div上设置overflow: hidden。要使溢出的图像居中,请使用绝对定位和一些JavaScript根据图像的大小设置topleft值。

修改:如果图片大于两个维度中的容器,请使用一些JavaScript删除minHeightminWidth,然后设置height100%。如果在宽度上留下空格,请将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

答案 1 :(得分:2)

编辑:

fiddle

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;
}

我不知道如何扩展小图片以适应,而不是缩小大图像。

答案 2 :(得分:0)

如果你的意思是你需要在面向风景的图像上面没有包括的空白(例如照片需要填充方块,无论它原来是方形),然后你可能想要将图像设置为div的背景并使用background-size: cover。有关浏览器支持,请参阅this link

答案 3 :(得分:0)

做到这一点的最佳方法是使用对象适合属性。

.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

相关问题