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 (9 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]


Horizontal centering:
margin-left: auto;
margin-right: auto;


Vertical centering:
Requires a container div. Set your outer div to to be relatively positioned, set your inner div as absolute positioning and top: 50%.
posted by floam at 12:35 AM on May 17, 2009


Oh, you'll also need to offset the height of your inner div, so set margin-top: -150px, which is half of 300.
posted by floam at 12:37 AM on May 17, 2009


What mattoxic did is relying on things handling CSS incorrectly, especially for horizontal centering where no tricky stuff is necessary.
posted by floam at 12:38 AM on May 17, 2009


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


XMLicious: I'm pretty certain he's relying on undefined behavior when setting top for something neither absolutely nor relatively positioned.
posted by floam at 3:33 PM 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


mattoxic: The other, larger difference is you didn't have position: absolute; in your first post.
posted by floam at 9:51 PM on May 21, 2009 [1 favorite]


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