Friday, July 27, 2012

Vertical Alignment of Elements in a DIV

The method for vertical alignment of text in a DIV is different from the common way, because of the style="vertical-align:middle;" used for table cells like elements doesn't work with DIVs.

As an alternative, if the length of the text is fixed, display the text inside a DIV with proper padding and margin settings will work. But when we have few lines of text and total height of the text is not fixed (that is variable length text, different font sizes, etc.), padding and margin will not work.

As a solution we can use CSS display Property with the value “table-cell” as in the below example.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <title></title>
  <style type="text/css">        
   #tablecellexamples div { border:1px solid black; width:130px; background-color:#eee }
  </style>
 </head>
 <body>
  <div id="tablecellexamples">          
   <div style="display:table-row">   
    <div>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin luctus dignissim ipsum a dignissim. Proin mattis orci sit amet quam feugiat lobortis.
    </div>
    <div style="display:table-cell; vertical-align:top">Top aligned</div>
    <div style="display:table-cell; vertical-align:middle">Center aligned</div>
    <div style="display:table-cell; vertical-align:bottom">Bottom aligned</div>
   </div>
  </div>
 </body>
</html>

The rendered page will look like below:

No comments: