0

Okay, so this question has been asked and answered many times, yet I still can't produce a working solution.

I'd like to vertically align to the middle arbitrary elements in a DIV. So, the linked-to tutorial in the above question says:

Specify the parent container as position:relative or position:absolute.
Specify a fixed height on the child container.
Set position:absolute and top:50% on the child container to move the top down to the middle of the parent.
Set margin-top:-yy where yy is half the height of the child container to offset the item up.

An example of this in code:

<style type="text/css">
    #myoutercontainer { position:relative }
    #myinnercontainer { position:absolute; top:50%; height:10em; margin-top:-5em }
</style>
...
<div id="myoutercontainer">
    <div id="myinnercontainer">
        <p>Hey look! I'm vertically centered!</p>
        <p>How sweet is this?!</p>
    </div>
</div>


Except contrary to what the screenshot on the tutorial shows, this doesn't work. The only thing I changed was to add a border around the outer DIV, so you can see the vertical alignment.

All this does is produce a zero-height DIV which renders like a straight line. If you add a height to the outer DIV, you can see the inner content, but it doesn't actually vertically align the content. So, why doesn't this example work?

Community
  • 1
  • 1
Channel72
  • 24,139
  • 32
  • 108
  • 180
  • Hey, I successfully centered the inner div, but it's late here, too lazy to think how to center the text. http://jsfiddle.net/HPN8e/2/ – Jeaf Gilbert Sep 11 '12 at 18:08

2 Answers2

0

I believe your containing div also has to have a specified height. If you inspect the #myoutercontainer div with firebug you see that it actually has a height of 13em, which they don't show in the example code given.

pivot
  • 105
  • 7
0

Here's a different approach based of this Chris Coyer article. If you want to vertically center the text to a fixed size div, then you can just repeat the process like so. If you want it to align to the right, just turn modify the "text-align: center;" style for myoutercontainer.

Bubbles
  • 3,795
  • 1
  • 24
  • 25