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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17320587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:19:35  来源:igfitidea点击:

Resize to fit image in div, and center horizontally and vertically

cssimagecenter

提问by Benjamin Crouzier

I have an image in a div. I would like the image to resize to fit the div, and be horizontally and vertically centered. I would like a solution that works in ie >= 8.

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

回答by Benjamin Crouzier

This is one way to do it:

这是一种方法:

Fiddle here: http://jsfiddle.net/4Mvan/1/

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

HTML:

HTML:

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

CSS:

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

回答by Hugo

Only tested in Chrome 44.

仅在 Chrome 44 中测试。

Example: http://codepen.io/hugovk/pen/OVqBoq

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

HTML:

HTML:

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

CSS:

CSS:

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

回答by filemono

NOT SUPPORTED BY IE

IE 不支持

More info here: 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>

回答by Ravi Soni

SOLUTION

解决方案

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