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:

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

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>
<dialog>
<form>
<label>Enter you email</label>
<input name='email' type='text' />
<input type='submit' />
</form>
</dialog>

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

html


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

css


.box{
 position:relative;
}
.box h1{
 display:block;
 position: absolute;
 left:0;
 top:50%
}

jQuery


$('.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?

E

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 .