ad box 728 x 90
ad box 468 x 60
Hardware, Software, Code, PHP, ASP, Games, Reviews and Other Funky Stuff
Subscribe

Enter your email address:

Pic of the Month
Popular Posts

How to easily center a div in the middle of the browser with CSS

I had to tackle this one recently, and didn’t want all the extra javascript libraries that go with the modal box window. I just needed to get a div and center it in the middle of the screen. Sounds easy enough hey, and it is once you know how. This works quite nicely cross most modern browsers, tested in Chrome, Firefox and IE. Ive included the inline CSS as well as the attached external CSS file.

Showing the demo of Centered Content

I just included this in a style tag but you can also assign it to a name in an external CSS if you wish ;)

First you have to know the dimentions of your div.

Mine was:

1
2
height: 200px;
width: 300px;

Then set the position to absolute.

1
position:absolute;

Then you need to get the top right hand corner of the div into the center of the browser using the top and left values as follows:

1
2
top:50%;
left:50%;

This will now make the corner of the div centered on the screen, but thats not really very helpful as is.

To get it right in the center, you need to set the margins to the negative of half of the width and height accordingly.

So if your width is 300px, then your left margin needs to be -150px; and the height is 200px; so the top margin should be set to -100px;

1
2
margin-top:-100px;
margin-left:-150px;

Right so now we have a nice centered div, which will stay centered even if you resize the browser window.

Also if you have issues with things appearing on top of your centered div you can always set the z-index of the div to a number greater than anything else on the page. Everything should start with a z-index of 0 unless it is set by something else like jquery or other css styles.

1
z-index:1;

Anyway back to the CSS in hand:

?Download style.css
1
2
3
4
5
6
7
8
9
10
.centered_div {
	height: 200px;
	width: 300px;
	position:absolute;
	top:50%;
	left:50%;	
	margin-top:-100px;
	margin-left:-150px;
	z-index:1;
}

and attach it to the div

1
2
3
<div class='centered_div'>
	centered content
</div>

or just do it the bad way, all inline ;) .. it works but its messy, and probably shouldnt be done this way.

1
2
3
<div class='centered_div' style='height: 200px;width:300px;position:absolute;top:50%;left:50%;margin-top:-100px;margin-left:-150px;z-index:1;'>
	centered content
</div>

You can see why the above method is not ideal especially if you had a large number of these div’s. Anyway it does work if you need something up quickly and dont already have a stylesheet.

Post Tags

This entry was posted on Wednesday, December 15th, 2010 at 12:28 pm and is filed under Web. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply

Spam Protection by WP-SpamFree