Vertically Centering an element with an unknown height

I’m trying to fully understand how to vertically center elements. I’ve read multiple articles and experimented with different techniques, but always end up falling back on hacks.

On one site there was a featured promo with markup like this:

   <h1>Here is my promo text</h1>
  <img src='my-image.jpg' />

The heading was centered in the div (which had a background image). The heading could have a different height depending on how long it was.
I ended up adding a timer to weight a few seconds before fading in the element after the dom had fully loaded.

Another issue is with lightbox dialogs. The kind with a translucent screen behind them.

I use markup like this.

<div id='screen'></div>
<label>Enter you email</label>
<input name='email' type='text' />
<input type='submit' />

The form is hidden until called. jQuery measures the height of the dialog a little short.

So my overall question is: What criteria are needed for jQuery to measure the height of an element correctly, and what techniques can you use to make sure these criteria are met?

Thank You E

Hi, eruna
you need to use jquery and css


<div class="box">
   <h1>Here is my promo text</h1>
  <img src='my-image.jpg' />


.box h1{
 position: absolute;


$('.box h1').css('margin-top',-$('.box h1').height()/2);

I’ve been having trouble with .height() measuring the element a little short. I’m assuming that its because jQuery is checking the height of an element that hasn’t been fully calculated by the browser yet. If the element is invisible until called, like in a popup window, how do you get the proper dimensions?


if an element is display:none you cant’ get the height , the best way is to replace display:none; with opacity:0 , may be with more details I can help you .