core error

Center align a DIV

Posted on: 29/09/2011


Many times we need to center align a DIV inside another div. If we know the width of the inner DIV in before hand it is really simple, we can just add the width, margins to 0px and auto and that’s it:

div.inner {
	width:500px;
	margin:0px auto;
}

BUT, things may be more complicated if we don’t know the width of the inner DIV. In this case we need use a different type of display for the DIV (inline-block) and make sure that the outer div text-aligns everything to the center:

div.outer {
	text-align: center;
}
div.inner {
	display: inline-block;
}

The reason to this is that DIVs are by default display: block. This kind of display expands to the entire width except if we specify a fixed width but in this case, margin:0px auto. The inline-block display wraps its size around the its contents and allows to be aligned as text inside a div.

Note: Since IE7 doesn't understand the inline-block property, it will be needed to make a small hack to the inner div class for IE7 to work properly:

div.inner {
	display: inline-block;
	zoom: 1;
	*display: inline; #this will be ignored by all browsers except IE
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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


    • Justin Cooney: Great comic, this made me laugh!
    • Justin Cooney: Interesting, I didn't know about the Google App Engine, I'm glad I found your article on it!

    Categories

    %d bloggers like this: