SO 上有很多关于垂直对齐的问题,但我还没有找到我的问题的明确答案。
我创建了一个 fiddle 以准确显示我正在尝试做的事情。
HTML:
<div id="fade"></div>
<div id="fullscreen">
<img src="http://jira.seraphdevelopment.com/jmajewski/clean/uploads/pictures/n8jvxzd2476480d0.jpg" />
</div>
CSS:
#fade {
/* Cover the entire viewport. */
position: fixed;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
/* Transparent Background */
background-color: #000;
opacity: 0.50;
}
#fullscreen {
/* Cover the entire viewport. */
position: fixed;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#fullscreen img {
/* Adding the display: block allowed me to center
the image horizontally with the margin: auto. */
display: block;
margin: auto;
/* Limit the size of the image. */
max-width: 80%;
max-height: 80%;
/* This didn't work for me. */
vertical-align: middle;
/* This didn't do anything, either. */
line-height: 100%;
}
我正在尝试制作某种类型的灯箱,以便用户单击页面上的图像,从而使同一图像以全屏模式加载。第一个div
,fade,会用半透明的黑色背景覆盖整个页面,本质上是给出页面淡出的效果,同时也使东西模态。
我希望能够将图像嵌套在 fade div
中,但遇到了问题。在外部 div 上设置不透明度(以创建淡入淡出效果)导致我的嵌套图像继承不透明度值。因此,我添加了一个与第一个相同的单独 div
,只是没有背景,并将图像嵌套在其中。
郑重声明,我确实设法找到了解决不透明度问题的方法,但我还没有实现它。感谢 Blowski,一位 SO 用户发布了关于不透明度问题的答案:
I do not want to inherit the child opacity from the parent in CSS
长话短说,为了让这张图片垂直居中,我已经尝试了很多方法,但都无济于事。
请记住,此解决方案需要适用于任何图像!
我当然可以在 $(window).resize()
函数中添加一行代码来手动将图像居中,但我想尽可能避免这样做。我非常想知道解决这个问题的方法,因为我似乎更频繁地遇到这些类型的问题。
额外奖励:为什么垂直对齐对于浏览器来说执行起来如此困难?
最佳答案
这是使用 CSS 将图像置于固定/绝对定位的 div
中的一种方法。
#fullscreen {
/* Cover the entire viewport. */
position: fixed;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#fullscreen img {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
/* Limit the size of the image. */
max-width: 80%;
max-height: 80%;
}
诀窍是对img
使用position: absolute
并将所有偏移设置为0,然后margin: auto
将居中图片。
max-width
和 max-height
值将按预期工作。
之所以可行,是因为图像具有固有尺寸,因此 CSS 引擎具有特定值来进行必要的数学运算,使图像在垂直和水平方向上居中。
参见演示:http://jsfiddle.net/audetwebdesign/KG99S/
评论
请注意,此技术独立于叠加层工作。
此外,无论图像的宽高比如何,这都有效。
引用
此技术遵循 CSS2 规范,关于如何确定绝对定位的内联替换元素的水平和垂直边距。
http://www.w3.org/TR/CSS2/visudet.html#abs-replaced-width
和
关于javascript - 在固定位置 Div 中垂直居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702865/