调整大小以适合div中的图像,并水平和垂直居中

时间:2013-06-26 12:53:06

标签: css image center

我在div中有一个图像。我希望图像调整大小以适应div,并且水平和垂直居中。我想要一个适用于ie> = 8的解决方案。

4 个答案:

答案 0 :(得分:37)

这是一种方法:

在这里小提琴:http://jsfiddle.net/4Mvan/1/

<强> HTML:

<div class='container'>
    <a href='#'>
    <img class='resize_fit_center'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
    </a>
</div>

<强> CSS:

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

答案 1 :(得分:19)

仅在Chrome 44中测试过。

示例:http://codepen.io/hugovk/pen/OVqBoq

HTML:

<div>
<img src="http://lorempixel.com/1600/900/">
</div>

CSS:

<style type="text/css">
img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    max-width: 100%;
    max-height: 100%;
}
</style>

答案 2 :(得分:1)

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

答案 3 :(得分:1)

不受IE支持

此处有更多信息:Can I Use?

.container {
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.container img {
  object-fit: cover;
  width: 100%;
  min-height: 100%;
}
<div class='container'>
    <img src='http://i.imgur.com/H9lpVkZ.jpg' />
</div>