I have the following HTML for a sort-of lightbox project.
th
To vertically center an item you need the following 2 css attributes :
display:table-cell;
vertical-align:middle;
example : http://jsfiddle.net/yjv94/
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 div
s. The centered div
's width can even be a percentage (which was what I was looking for when I found this solution).
Here are couple SASS mixins I'm using... I hope this is going to help someone:
// vertically centers as relative
@mixin vertical-align {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
// vertically centers the element as absolute
@mixin vertical-center {
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
// horizontally centers the element as absolute
@mixin horizontal-center {
position: absolute;
left: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
// absolutely centers the element inside of its first non-static parent
@mixin absolute-center {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
If you want the image to have a fluid size, you can use the height of the view as a reference:
#img {
position: relative; /* or absolute or fixed depending on your needs */
top: 50%;
height: 80vh;
margin-top: -40vh; /* minus half the height */
}
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;
}
have you check this soution?:
CSS: Vertically align div when no fixed size of the div is known
here you dont need to have a height declared.
Regards