Centering with CSS
Back in the old days, if you wanted to center your whole (fixed size) page both horizontally and vertically in the browser window, you’d add an extra wrapper table, set its width and height to 100% and use the align and valign attributes on the single cell of that table to achieve the effect.
Then Web Standards were rediscovered.
To make modern browsers behave in a more predictable way they need a correct DOCTYPE. That will also make some of them refuse to make a table’s height 100%, since that was never part of the HTML specification (though widely accepted by browsers). So we can’t use the table trick anymore even if we wanted to mess up our neat, table free code.
What are the options, then, assuming we absolutely must center everything?
I have found two approaches. One is to settle for horizontal centering. It works well in most modern browsers, and there is a trick to make it work in IE5/Win too. Mozilla and sometimes Opera both like to push content off the page to the left when the window is made narrower than the content. This is prevented by setting the body’s min-width to the width of the centered object.
The second method gives us both horizontal and vertical centering. This requires that the width and height of the centered block are known. The drawbacks are that it doesn’t work well in IE5/Mac, and that if the browser window is made smaller than the centered object, the negative margins used will push the content off the page to the left and top.
More resources on centering with CSS:
- Web Page Design for Designers: Vertical Centring with CSS
- Hicksdesign: vertical centering with CSS
- Bluerobot: Centering: Auto-width Margins
- HTML to CSS: Center the page vertically and horizontally
- Owen Briggs: The centered box
Subscribe / follow
- Senior UI Developer (Angular.js, html5/css3, symfony, etc.)
- Lead Visual Designer - Product at Fitbit (San Francisco, CA, Ca, US)
- Sr. Python Engineer @ Brilliant at The Sourcery (Palo Alto, CA, US)
- Mobile web MVP project for a startup at Vendalize
DreamHost web hosting
Use the promo code 456BEREASTREET3 to save USD 20 when you sign up for DreamHost