【发布时间】:2014-08-09 00:19:31
【问题描述】:
我试图让图像在高度和宽度可变的 div 中水平和垂直居中。 到目前为止,一切顺利。(请参阅下面的 jsfiddle 链接)
现在要注意的是,如果容器的高度和/或宽度小于图像的高度或宽度,图像也应该具有响应性并进行调整。
经过研究,通过所有不同的“解决方案”并摆弄解决方案,我无法找到完美的解决方案,但有两个接近了:
1.) 第一个可以满足我的所有需求,除非窗口宽度小于图像宽度,图像不再水平对齐:
http://jsfiddle.net/me2loveit2/ejbLp/8/
HTML
<div class="overlay">
<div class="helper"></div>
<img src="http://dummyimage.com/550x480/000/fff?text=H/V Centered and height/width variable">
</div>
CSS
.helper {
height:50%;
width:100%;
margin-bottom:-240px;
min-height: 240px;
}
.overlay {
width: 100%;
height: 100%;
position: fixed;
top: 0px;
left: 0px;
cursor: pointer;
background-color: rgba(0, 0, 0, 0.5);
}
img {
margin: 0 auto;
max-width: 100%;
max-height: 100%;
display: block;
}
2.) 第二个示例保持所有内容对齐,但当高度小于图像高度时,图像不会缩小:
http://jsfiddle.net/me2loveit2/ejbLp/9/
HTML
<div id="outer">
<div id="container">
<img src="http://dummyimage.com/550x480/000/fff?text=H/V Centered and height/width variable">
</div>
</div>
CSS
#outer {
height:100%;
width:100%;
display:table;
position:fixed;
top:0px;
left:0px;
background-color: rgba(0, 0, 0, 0.5);
}
#container {
vertical-align:middle;
display:table-cell;
max-width: 100%;
max-height: 100%;
}
img {
margin: 0 auto;
max-width: 100%;
max-height: 100%;
display:block;
}
【问题讨论】: