My div, in the middle of my page, my div… ♫

In a hurry? Check the demo!

So… you want to nicely position a div in the middle of a page (equal distance top/bottom and left/right).

Easy-peasy.

Here we go. I’ll show you only the method based on CSS, because the table-based method is really deprecated and every time you use it, God kills a baby panda.

First, let’s create the basic page structure:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>labs.moldoveanu.net - My div, in the middle of my page, my div... ♫</title>
</head>

<body>
    <div id="bogus"></div>
    <div id="myCenteredContent">
        <p>Whooohoooo! I'm centered, dude!</p>
    </div>
</body>
</html>

Now, put the following block in a separate CSS file (or directly in the head tag):

		html,body {
		  height:100%; /* required */
		}

		body {
		  background-color:rgb(255,255,255); /* purely cosmetic, can be safely removed */
		  margin:0; padding:0; /* required - sticking #helper on a side */
		  text-align:center; /* centering hack for the mighty IE */
		}

		div#bogus {
		  /* background:rgb(0,0,0); */ /* remove it - only for testing */
		  float:left; /* required */
		  height:50%; /* required - */
		  margin-bottom:-75px; /* required - half of the #myCenteredContent height */
		  width:1px; /* required - */
		}		

		div#myCenteredContent {
		  border:1px solid rgb(128,128,128);/* purely cosmetic, can be safely removed */
		  clear:left; /* required */
		  height:150px; /* required - height of the visible centered content */
		  margin:0 auto; /* required */
		  padding:0; /* cosmetic */
		  position:relative; /* required */
		  text-align:center; /* cosmetic - aligning the content inside the #myCenteredContent */
		  width:600px; /* required - width of the visible centered content */
		}

Please note: if you try to center a SFWObject, please follow this page and have a look at the demo. Quick hint: you have to declare the object tag, too:

object#myYouTubeVideo {
	clear:left;
	display:block;
	margin:0 auto;
}
Posted at Dec 8th | no comments | Filed Under: How to, Web development read on

 



About this entry