Abdu Abdu - 4 years ago 181
HTML Question

vertical alignment of elements in a div

I have a div with two images and an

. All of them need to be vertically aligned within the div, next to each other.

One of the images needs to be
positioned within the div.

What is the css needed for this to work on all common browsers?

<div id=header">
<img src=".." ></img>
<img src="..."></img>

Answer Source

Wow, this problem is popular. It's based on a misunderstanding in the vertical-align property. This excellent article explains it:

Understanding vertical-align, or "How (Not) To Vertically Center Content" by Gavin Kistner.

“How to center in CSS” is a great web tool which helps to find the necessary CSS centering attributes for different situations.

In a nutshell (and to prevent link rot):

  • Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example
  • For block elements, vertical alignment is harder and strongly depends on the specific situation:
    • If the inner element can have a fixed height, you can make its position absolute and specify its height, margin-top and top position. jsfiddle example
    • If the centered element consists of a single line and its parent height is fixed you can simply set the container’s line-height to fill its height. This method is quite versatile in my experience. jsfiddle example
    • … there are be more such special cases.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download