Tutorial: Vertical Centering

Okay, I admit it - centering a table or div horizontally is not all that hard. But what about centering vertically? If you've tried this, chances are, you've found that it's not quite so simple, particularly on a page without much content. You think you're setting height - and yet, for some reason your element sticks to the top part of your page.

As it turns out, what you are centering in is not the whole browser viewport, but only the part that has content. And this means that your stuff gets stuck at the top. You therefore need your body and HTML to fill up 100% of what contains them - the browser viewport.

The only way I know of to get something to center vertically on a page is to work with several elements: HTML, body, a 100% sized table, and the item you want centered. Thus, I would code this way:

html, body, #wrapper {
height: 100%;
margin: 0 auto;
padding: 0;
}
#centereditem {
margin: 0 auto;
width: 100px;
height: 100px;
background-color: yellow;
}

In the HTML for the above, #wrapper is to be applied to a single-cell table (not a div!) , and your #centereditem is inserted into that cell:

<table id="wrapper">
<tr>
<td><div id="centereditem"></div>
</td>
</tr>
</table>

Click here to see the result. (In this case, I also added 5px padding to the #centereditem div, so that the text wouldn't run up against the edge.)

Note: if you don't want the page to collapse all the way to the edge of your centered item, you can add a margin to the item:

#centereditem {
margin: 20px;
width: 100px;
height: 100px;
background-color: yellow;
}

See the example here.

Special thanks to Gary White for his tutorial here.

 

« Return to tutorials main index.

Update your web browser: Internet Explorer|Firefox|Opera|Safari (Win & Mac)

Protect
your computer:

ESET Smart Security - Save 25% NOD32 v3.0 - Save 25% - Download Now
G. P. Concrete Specialist siteColumbia Benefit siteCovenant Classical Christian School siteCone Consulting Group siteMetanarrative music project siteTrinity Presbyterian Church siteTruth and Beauty arts siteChrist Covenant church siteTrinity Reformation Church site

SELECT PORTFOLIO

Click on the monitor for more info about a site.

all our docs recent work

AFFILIATE

Customize your presentation with original music from MrGoJingles.