June 12, 2014

Alternative way to center a text element vertically with unknown parent height.

Centering a text element vertically in CSS is a crazy task. Because “vertical-align: middle” is not working sometimes. In fact, vertical-align works with Image only.

If you know the parent height already, you can set the line-height and height with same value in order to centering the element, for example:

line-height: 10px;
height: 10px;

However, what if I don’t know the height? You have 2 choices:

  1. Use table and set <td> with vertical-align: middle;
  2. You can re-style the button and make it look like a div.

The following link show it works.

http://jsfiddle.net/ptvkP/1/

these are strange and ugly ways, but works! 🙂