调整图像大小以占用所有<div> </div>

时间:2014-10-13 10:55:18

标签: html css

如何约束容器中的图像,以便整个容器尽可能多地填充图像?

例如(我不知道图像的大小,这只是一个例子) - 如果我有一个100x100的图像容器和600x400的图像,则需要满足以下条件。

  • 图像应以150x100
  • 显示
  • 图像应位于容器中心
  • 应隐藏图像溢出(本例中左右25px)。

请注意 - 某些图片的高度应大于宽度,因此任何解决方案都需要处理所有尺寸的图片,水平和垂直中心

可悲的是,任何解决方案也必须与IE9一起使用(因为这是我正在使用的内部网的所有者使用的浏览器),因此HTML5 / CSS3解决方案将无法正常工作。

以下是一些视觉示例 -

Example of image display 1 Example of image display 2

我尝试了各种CSS样式 -

  • 如果我将<img>嵌套在<div>容器内,则图像
  • 如果我绝对地将<img>放在<div>上,那么如果它比高(即600x400)宽,我就无法垂直居中。

我们将非常感激地收到任何建议。

3 个答案:

答案 0 :(得分:1)

不完全是您正在寻找的结果,但只有CSS,您可以尝试此演示:http://codepen.io/anon/pen/AotBk

相关CSS代码

.wrapper {
  width: 100px;
  height: 100px;
  overflow: hidden;
  position: relative;
  border: 2px dashed #ccc;
}

.wrapper img {
  position: absolute;
  left: 50%;
  top: 50%;
  max-width: 100%;
  max-height: 100%;
  transform: translateY(-50%) translateX(-50%); 
}

我使用了二维翻译,IE9即使{{1}}


三张图像(600x400,300x600和50x50)在100x100包装中产生效果的屏幕截图

enter image description here

答案 1 :(得分:1)

既然你提到它必须与IE9一起使用:background-size: cover就可以做到这一点。您不能将图像本身用作img元素,但必须将其作为背景图像分配给容器。

我为你做了一个jsfiddle here

答案 2 :(得分:-1)

试一试:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .container{
            width: 100px;
            height: 100px;
        }
        .container img{
            max-width: 100%;
        }
    </style>
</head>
<body>
    <div class="container">
        <img src="img/image.jpg"> <!-- here image width 600*400 -->
    </div>
</body>
</html>