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 comments total)
13 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 [2 favorites]
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
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
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
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
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
{
/* 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 [2 favorites]