Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

css vertically centering a fixed positioning div

I have the following HTML for a sort-of lightbox project.

<div id="lightbox">
  <img id="image" src="" />
</div>

that is using the following 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;
}

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.

I am facing problems with the vertical centering and I am using a workaround of simply setting the top value in the #lightbox properties.

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.

Any ideas? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best solution I've seen for both vertically and horizontally centering a position: fixed div is:

position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Fiddle and source. You don't need to know the dimensions of the div and it doesn't require any container divs. The centered div's width can even be a percentage (which was what I was looking for when I found this solution).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...