中有一张图片,我希望这张图片能够自适应div大小,并且水平垂直居中。我需要一种能够在ie >= 8浏览器中使用的解决方案。
这是一种方法:
在这里玩弄: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;
}
仅在 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>
position: relative
。 - halposition: relative
。谢谢。 - jfunk不受 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>
解决方案
<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>
<a>
和</a>
,它仍然可以工作。 (这确实不是问题的一部分,只是为了显示您可以将图像设置为链接而不会破坏它) - Benjamin Crouzier