将图像垂直居中在固定位置Div

时间:2014-07-11 16:57:39

标签: javascript css vertical-alignment opacity

关于垂直对齐,有很多关于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淡入淡出将用于覆盖整个页面,半透明的黑色背景,基本上可以使页面消失,同时还可以制作模态。 / p>

我希望能够将图像嵌套在淡入淡出 div中,但我遇到了问题。在外部div上设置不透明度(以创建淡入淡出效果)会导致嵌套图像继承不透明度值。因此,我添加了一个与第一个相同的单独div,除了没有背景,并将图像嵌套在其中。

为了记录,我确实设法找出了不透明度问题的解决方法,但我还没有实现它。感谢 Blowski ,SO用户将此答案发布到有关不透明度的问题:

I do not want to inherit the child opacity from the parent in CSS

长话短说,我现在尝试了很多东西试图让这个图像垂直居中,但无济于事。

请注意,此解决方案需要使用任何图片!

我当然能够在$(window).resize()函数中添加一行代码来手动居中图像,但如果可能的话,我希望避免这样做。我非常好奇地学习解决方法,因为我似乎经常遇到这类问题。

Bonus:为什么浏览器执行垂直对齐这么难?

1 个答案:

答案 0 :(得分:2)

以下是使用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%;
}

诀窍是对position: absolute使用img并将所有偏移设置为0,然后margin: auto将图像居中。

max-widthmax-height值将按预期工作。

这样做的原因是图像具有固有的尺寸,因此CSS引擎具有特定的值来进行必要的数学运算以使图像在垂直和水平方向上居中。

请参阅演示:http://jsfiddle.net/audetwebdesign/KG99S/

<强>评论

请注意,此技术与叠加层无关。

此外,无论图像的宽高比如何,这都有效。

<强>参考

这项技术遵循CSS2规范,关于如何确定绝对定位的内联替换元素的水平和垂直边距。

http://www.w3.org/TR/CSS2/visudet.html#abs-replaced-width

http://www.w3.org/TR/CSS2/visudet.html#abs-replaced-height

相关问题