tkbx
tkbx

Reputation: 16305

margin: auto doesn't center?

I'm trying to center a div on the document, and it works horizontally, but not vertically:

width: 950px;
height: 630px;
background: #FFFFFF;
margin: auto;

Shouldn't margin: auto place it in the center of whatever it's in (the page itself, in this case)? I used to have a workaround for this, but I can't get it to work. It would also be nice to know what I'm doing wrong, so I can stop doing it.

Upvotes: 2

Views: 1268

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 220136

margin: auto does not align elements vertically.

If you have to support older browsers, you'll have to define a fixed height for your div:

div {
    position: relative;
    top: 50%;
    width: 750px;
    height: 500px; /* sample. adjust as needed */
    margin: -250px auto 0; /* half the height */
}

Here's the fiddle: http://jsfiddle.net/2qmVX/


If you don't care about IE8 and below, this'll allow you to retain your fluid height:

div {
    position: relative;
    top: 50%;
    margin: auto;
    transform: translateY(-50%);
    /* add prefixed versions... */
}

Here's the fiddle: http://jsfiddle.net/VMaVM/ (remember: modern browsers only).


Update: As pointed out by @FabrícioMatté, you also have to apply 100% height to the html & body elements:

html, body {
    height: 100%;
}

See the demos above.

Upvotes: 6

Fabrício Matté
Fabrício Matté

Reputation: 70199

Proper vertical centering is something that not even CSS3 covers yet.

Luckily in your case, as you have a fixed height, you can maneuver the top/left properties and use negative margin-top and margin-left to attain the desired behavior, with absolute positioning:

background: #FFFFFF;
width: 950px;
height: 630px;
top: 50%;
left: 50%;
margin: -315px 0 0 -425px; /*top is negative half of height, same for width*/
position: absolute;

Demo / source

Beware that negative margins may behave unexpectedly on resolutions smaller than the div.


Here's a slightly more hackish way, using a table. The basic idea is that the vertical-align:middle CSS property when applied to a table has the same effect as the old valign="center" attribute. So the HTML would looks like this:

<table class="vcenter"><tr><td>
    <div id="myDiv">This is a centered div</div>
</td></tr></table>

And the CSS:

.vcenter {
    vertical-align: middle;
    width: 100%;
    height: 100%;
}
#myDiv {
    background: #FFF;
    width: 950px;
    height: 630px;
    margin: 0 auto;
}
html, body { height: 100%; }

Demo / source

Advantages of this method is that it is completely cross-browser - tested on IE6 and up, Firefox, Chrome, Opera and Safari. I didn't test on mobile browsers though it should work. Also it doesn't have the scrolling issue with small resolutions. I use this hack for centered modals in one of my production sites.

Upvotes: 3

Related Questions