Vertical-Align text inside a DIV container with CSS

Text-Align, the simple case

Aligning text in a DIV container ist very simple done by the following code:

  <div style="width:100%; text-align:center;">Centered Text</div>

Vertical-Align - the complicated case

Vertical alignment of text in a DIV is a little bit more complicated, because the usual way used for table cells doesn't work with DIVs.

The code below doesn't work:

  <div style="height:3em; vertical-align:middle;">
    Not centered vertically!
  </div>

The reason is, vertical-align doesn't work for block elements by definition. Instead its usage is limited to define the alignment of inline elements. To align the text vertically, you have two choices.

The solution!

1. display the text inline with a vertical aligned DIV like:

  <div style="height:3em;">
    <div style="height:3em; width:0;
                visibility:hidden;
                vertical-align:middle;
                display:inline"></div>
    Centered vertically!
  </div>

-or- (to with less code and just a single div)-
2. display the text inside a DIV with proper padding and margin settings:

  <div style="height:3em;padding:1em 0 1em 0">
    Centered vertically!
  </div>

Thank you! I am coding CSS

Thank you! I am coding CSS very rarely, and I constantly forget how to vertical-align inside a div :)

I'm glad it helps! Well,

I'm glad it helps! Well, actually I think one should avoid vertical alignment. For most layouts it is sufficient to use CSS floating and margins. Vertical alignment is favoured by people like us usually not feeling too convenient with CSS and missing the TD style "vertical-align". Perhaps I'll write a short article about floating DIVs and some nice margin usage.

Not any solution :-(

Not any solution :-(

If the article doesn't help,

If the article doesn't help, you have two options:

1. Ckeck your concept for errors. No up-to-date website design requires old-school <td vertical-align>!
2. Ask a question to get a second opinion about your problem.

Post new comment

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is to verify you're a human visitor with at least everage IQ. Please do not use a calculator.
1 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.