css垂直居中一个固定的定位div [英] css vertically centering a fixed positioning div
问题描述
我有一个类别的Lightbox项目的以下HTML。
I have the following HTML for a sort-of lightbox project.
<div id="lightbox">
<img id="image" src="" />
</div>
使用以下CSS:
#lightbox{
display:none;
position:fixed;
width:100%;
text-align:center;
z-index:600;
cursor:pointer;
left:0;
top:100px;
}
#image{
position:relative;
height:600px;
border:1px solid grey;
}
为了使图像始终处于水平中心, align:中心在包装div,所以我100%肯定它是正确的。
To have the image always in the horizontal center, I am simply using text-align:center on the wrapper div, so I am 100% sure it will be correct.
我面临垂直中心问题,我使用一个解决方法设置#lightbox属性中的顶部值。
I am facing problems with the vertical centering and I am using a workaround of simply setting the top value in the #lightbox properties.
正如你可以看到的图像的高度是已知的,所以它很容易在jQuery中做,但我正在寻找一个纯CSS解决方案。
As you can see the height of the image is known, so it is easily doable in jQuery but I am looking for a pure CSS solution.
任何想法?
推荐答案
或者,您也可以尝试这个方法(只有在知道图片高度的情况下才有效):
Alternatively, you could try this (only works if you know the height of the image):
#image{
position:relative;
height:600px;
top: 50%;
margin-top: -300px; /* minus half the height */
border:1px solid grey;
}
这篇关于css垂直居中一个固定的定位div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!