Replace valign with CSS

For those trying to break away from using tables for layout and do things in CSS, the loss of the valign attribute is a problem.  For some reason, the CSS people never imagined that we’d want to center anything vertically.

You might have tried to use the CSS vertical-align property in your div and discovered it had no effect.  The reason for this is that div is a block element and vertical-align only applies to inline elements.  So we need to use an inline element like span.  But wait, you say, inline elements can’t have a height specified!  Quite so.  But we can emulate height with the line-height property.  So we just wrap the content to be centered in an inline element with a line-height that’s the same as the parent block’s height and presto!

For example:

<div style="width: 200px; height: 50px; text-align: center; border: 1px solid;">
     <span style="line-height: 50px; vertical-align: middle;">
          Vertically centered!
     </span>
</div>

Vertically centered!

 It’s a bit of a hack, but what about web design isn’t?  :)

One Response to “Replace valign with CSS”

  1. rd Says:

    Thanx.I have been facing this problem for a long time.

Leave a Reply