How do I vertically center an H1 in a div?

Edward Touw picture Edward Touw · Dec 13, 2013 · Viewed 106.8k times · Source

First of all, my apologies. I know there are various solutions posted for this issue here, but for the life of me I can't get any of them to work.

For a responsive website I'm trying to center an h1 in a div.

Centering horizontally is not an issue, but I'm having problems getting it centered vertically. Presumably I'm doing something wrong or misunderstanding the explanations I found here (or maybe both).

So as I'm probably interpreting earlier solutions given the wrong way, could someone please explain what exactly I have to add to the code beneath to get the h1 to center vertically?

(To make this question relevant to as much people as possible, I've already stripped the code of all my previous attempts to do so myself.)

CSS:

html, body {
height: 100%;
margin: 0;
}

#section1 {
min-height: 90%; 
text-align:center
}

HTML:

<div class="section" id="section1">
<h1>Lorem ipsum</h1>
</div> 

Answer

Pete picture Pete · Dec 13, 2013

you can achieve vertical aligning with display:table-cell:

#section1 {
    height: 90%; 
    text-align:center; 
    display:table;
    width:100%;
}

#section1 h1 {display:table-cell; vertical-align:middle}

Example

Update - CSS3

For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:

#section1 {
    height: 90%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}

Updated fiddle