You can use top:50%;
and margin-top:-38px;
on #floatingBarsG
like this:
#floatingBarsG{
...
top:50%;
margin-top:-38px;
}
The margin-top
needs to be the half of the height
.
Check the demo to see its working.
Question
I've searched and read other posts, but none seem to work for me. I simply have an overlay that I toggle which has a loading animation. I need the animation to be horizontally and vertically centered. I can't get the vertical piece to work. CSS for overlay div and div that contains animation:
#pageOverlay {
opacity: 0.5;
background: #000;
width: 100%;
height: 100%;
z-index: 10;
top: 0;
left: 0;
position: fixed;
cursor: wait;
}
#floatingBarsG{
position:relative;
width:62px;
height:77px;
margin: auto;
}
HTML:
<div id="pageOverlay">
<div id="floatingBarsG">
<div class="blockG" id="rotateG_02"></div>
<div class="blockG" id="rotateG_03"></div>
<div class="blockG" id="rotateG_04"></div>
<div class="blockG" id="rotateG_06"></div>
<div class="blockG" id="rotateG_07"></div>
<div class="blockG" id="rotateG_08"></div>
</div>
</div>
Solution
You can use top:50%;
and margin-top:-38px;
on #floatingBarsG
like this:
#floatingBarsG{
...
top:50%;
margin-top:-38px;
}
The margin-top
needs to be the half of the height
.
Check the demo to see its working.
OTHER TIPS
Since your #floatingBarsG
div has a fixed width and height, you can use the following CSS:
#floatingBarsG{
position:absolute; /* Change the position to absolute. */
width:62px;
height:77px;
top:0;
right:0;
bottom:0;
left:0;
margin: auto;
}
By changing the position
to absolute
, and by setting the top
, right
, bottom
, and left
properties, combined with margin: auto
, your loading div will vertically center itself.
Keep in mind that this method of vertical centering only works when your centered element has a fixed height or a minimum height, and when its parent element has a position
that is not static
.
C Travel's solution is more cross-browser (mine won't work in IE8 and below, I believe), but only works with a fixed height.
How about this (I added a border around the animation for clarity):
#pageOverlay {
opacity: 0.5;
background: #000;
width: 100%;
height: 100%;
z-index: 10;
top: 0;
left: 0;
position: fixed;
cursor: wait;
}
#floatingBarsG{
border: 1px solid #f00;
position:relative;
width:62px;
height:77px;
top: 50%;
margin: auto;
margin-top: -38px;
}
Since no one else seems to be posting examples using line-height, here's mine:
This works by having a parent with a fixed height and line height:
.parent { height: 50px; line-height: 50px; }
and then using these properties on the child:
.child { display: inline-block; vertical-align: middle; }