1097

I have a div with two images and an h1. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be absolute positioned within the div.

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

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>
3
  • 25
    I made a list of all ways to vertical align..I am going to leave it here: jsfiddle.net/techsin/FAwku/1 Commented May 22, 2014 at 17:27
  • 3
    Here are two simple methods to center an element within a div, vertically, horizontally or both (pure CSS): stackoverflow.com/a/31977476/3597276 Commented Aug 20, 2015 at 15:24
  • 1
    margin-top: auto and margin-bottom: auto (Works for alot of cases). Commented May 13, 2020 at 23:46

31 Answers 31

1
2
-8
<div id="header" style="display: table-cell; vertical-align:middle;">

...

or CSS

.someClass
{
   display: table-cell;
   vertical-align:middle;
}

Browser Coverage

Sign up to request clarification or add additional context in comments.

6 Comments

The vertical-align property does not apply since the div is display: block by default and nothing appears to have been done to change it.
Apparently the display was updated to table-cell, which makes vertical-align: middle; work. Even better, it works without needing a nested wrapper/buffer div, and it works for both text and images (or both), and you don't need to change the position properties.
This one works. It changes the display to table-cell which takes the vertical-align property. No idea why people vote this down.
yes, as far as i know this is the least intrusive way to center anything verticaly in a div. +1
Ok, maybe i was too quick with my conclusions... Adding display:table-cell breakes div margin and additionaly border is displayed outside div, border combined with border-radius displays rounded corners inside of the div istead of outside
|
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.