Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Centering text vertically in a div.

What is the best practice when centering text vertically in a div? In the below a padding-top of 10px was used and the vertical alignment was eye-balled,

HTML

<div class="banner"> <h1 class="bannerheading">Heading</h1> </div>

.banner { background: #1f1f2e; width: 100%; height: 90px; padding: 5px; text-align: center; margin-bottom: 40px; }

.bannerheading { color: white; text-transform: uppercase; padding-top: 10px; }

***************Also found the below on stack overflow when using a span inside a div, but was under the impression that best practice is to use line-height with no unit.

div { width: 250px; height: 100px; line-height: 100px; text-align: center; }

span { display: inline-block; vertical-align: middle; line-height: normal;
}

Use the CSS andHTML format, that would help to understand more easy your code :)

1 Answer

Hi Curt,

Personally I don't see a problem with the line-height having a 'unit' defined as this was the best way to do it 'back in the day'.

These days I see a lot of 'display:table' where it mimics the table layout, which includes 'vertical-align' from table layouts.

I have the two styles below.

CSS

    body { margin:0; padding:0; }
    .bannerHeading {
        background:#1f1f2e;
        width:100%;
        height:90px;
        line-height:90px;
        text-align:center;
        color:white;
        text-transform:uppercase;
    }

    .bannerHeading2 {
        display:table;
        width:100%;
        height:90px;
    }
    .bannerHeading2 h1 {
        display:table-cell;
        vertical-align:middle;
        background:#1f1f2e;
        width:100%;
        height:90px;
        text-align:center;
        color:white;
        text-transform:uppercase;
    }

HTML

    <h1 class="bannerHeading">Heading</h1>

    <div class="bannerHeading2"><h1>Heading</h1></div>

Thanks, Damien! It helps to have yet another option to accomplish this.