Custom Web Design by Rainbo Design

Centering Elements with CSS

There are very few references for using CSS to center elements, so I hope this helps. You can use the 'align' attribute on some HTML elements or revert to the <center> tag, but these are depreciated website design techniques that have limitations that you may want to avoid.

But that still leaves the question of centering elements with CSS. The best approach is to use set the appropriate margin setting to "auto" on any block-level element to be centered, and using "text-align:center" to center inline elements within a block-level element. Use the "View Source" command in your browser to examine the HTML for this page. Be sure to check out the CSS style commands in the <head> section, and then look for the <div> tag in the code with the class attribute of "cellContainer".

This text is contained in a pair of nested <div>s: an inner <div> (class 'cellBody' in this document) and an outer container <div> (class 'cellContainer'). The outer <div> is set to a width of 100% which it inherits from the parent containing element. The parent in this case is the whole document - specifically, the <body> tag, but it could be another <div> or a <td> within a <table>. The inner <div> that encloses the content to be centered has its width set to 75% of the width of its parent block-level element. The concept of the containing element is one you need to absorb when dealing with CSS because, after all, it's the "cascading" capabilities of CSS that are so fundamental.

To center the image within the already-centered <div> that holds this text block, I enclosed the <img> inline element with a <p>aragraph tag, and used "text-align:center" on the <p> tag.

mechanic image

But the key is that the margin of the inner <div> has its left and right settings set to "auto" which automatically adjusts to the size of the viewport as the window is resized, keeping the element(s) contained in the inner <div> perfectly centered. You can center an element vertically with the same technique by setting the top and bottom margins to "auto" in the same fashion, as long as the height of the inner <div> is set appropriately. You can use this technique anywhere on your page, since it does not rely on absolute positioning or nested <table> tags that can get difficult to maintain and edit as your webpage design changes.



CSS Tutorial Main Page
Tools and Scripts Menu


Copyright © 2005-2009 by Richard L. Trethewey. It's not that I think this is such an earth-shatteringly great presentation, but if you want to copy it, I'd appreciate it if you would ask for permission.

Rainbo Web Design Sitemap

home page icon Website Design by Rainbo Design Main Page