Centering a div element
May 17, 2009 12:24 AM   Subscribe

What is your favorite method to get <div style="width:400px;height:300px;"> to be in the center of a page (both horizontally and vertically)? Preferably CSS rather than tables.
posted by jgunsch to Computers & Internet (4 answers total) 10 users marked this as a favorite
 
First, tables should not be ignored as a layout method, they are perfectly acceptable- and css div purists are the last people you want to meet at parties

div#mattoxic
{
/* the horizontal aligning definitely works */
left: 50%;
margin-left: -250px;
width:500px;
/* the vertical aligning *should* work */
height:500px;
top: 50%
margin-top: -250px;
}
posted by mattoxic at 12:32 AM on May 17, 2009 [2 favorites]


floam, what is mattoxic doing that relies on things handling CSS incorrectly? 'top' and 'left' are both allowed to have percentage values and negative values for margin properties are allowed so I'm not clear what you're referring to.
posted by XMLicious at 4:22 AM on May 17, 2009


Saw a quiz on how to center recently. Solution is here, with explanation and cross-browser caveats.
posted by samsm at 5:25 AM on May 17, 2009


Floam, you are quite right, the vertical aligning in my initial example will not work, however, if I add the missing semi colon -

div#mattoxic
{
position:absolute;
left: 50%;
margin-left: -250px;
width:500px;
height:500px;
top: 50%;
margin-top: -250px;
border:1px solid #000;
}

it works perfectly- IE7 (ie6 too from memory) FF & Safari and is quite legal.
posted by mattoxic at 8:08 PM on May 18, 2009


« Older Headphone recommendations for road cycling?   |   And what of petabytes? Will they simply be "pets"? Newer »
This thread is closed to new comments.