DevHints

CSS: Centering Block-level Elements: DIVs and Tables

Posted on: October 29, 2006

Centering your tables and divs can be confusing since not all browsers play nice with applying the parent element’s text-align attribute to block-level elements. No worries though, there is a quick and easy way to center any block level element.

margin: 5px auto;

As you should already know, when you set margin or padding you can alter all the sides individually like this:

attribute: top left bottom right;
attribute: topandbottom sides;
attribute: top sides bottom;

So in the example above, we set the margin for the top and bottom to 5px and the sides to auto. When you set the sides to auto, the browser will center it in it’s parent element because it makes the margins the same on each side. You could also set the top and bottom separately like this:

margin: 5px auto 10px;

So there you have it: the magic way of centering block-level elements in CSS!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: