Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css vertically centering a fixed positioning div

Tags:

css

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.

like image 979
john smith Avatar asked Jan 29 '13 13:01

john smith


People also ask

How do I vertically center a div inside another div?

Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.

How do you vertically align a div in CSS?

For this to work, you need to have a parent container with the display: table; property, and inside that container you will have the number of columns you want to have centered, with the display: table-cell; (and vertical-align: middle; ) property.


2 Answers

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).

like image 136
Vincent Avatar answered Oct 10 '22 00:10

Vincent


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;
}
like image 22
Gareth Cornish Avatar answered Oct 10 '22 01:10

Gareth Cornish