Wednesday, April 11, 2012

Vertical alignment of element

Link here

2 methods to align a child element inside a parent element ->

1)

The following example makes two (non-trivial) assumptions. If you can meet these assumptions, then this method is for you:

    You can put the content that you want to center inside a block and specify a fixed height for that inner content block.
    It's alright to absolutely-position this content. (Usually fine, since the parent element inside which the content is centered can still be in flow.

If you can accept the above necessities, the solution is:

    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>

2)

This method requires that you be able to satisfy the following conditions:

    You have only a single line of text that you want to center.
    You can specify a fixed-height for the parent element.

If you can accept the above necessities, the solution is:

    Set the line-height of the parent element to the fixed height you want.

An example of this in code:

<style type="text/css">
 #myoutercontainer2 { line-height:4em }
</style>
...
<p id="myoutercontainer2">
 Hey, this is vertically centered. Yay!
</p>

No comments:

Post a Comment