user2209563 user2209563 - 4 months ago 13
CSS Question

Centering <div> without using "margin: auto;"

I'm looking for a way to center a div horizontally in the page on Google Chrome.

I tried using margin: auto; but I've read that this function is not supported in Google Chrome. As a result my div stays aligned to the left side of the screen.

If I use, for example, margin-left: 100px; the div does move toward the center of the page, but I don't want to center it manually.

HTML:

<body>
<div id="header">
<p>John Doe</p>
<p>email</p>
</div>
</body>


CSS:

body
{
background-color: #f0f0f0;
}

div
{
border-radius: 5px;
}

#header
{
position: fixed;
background-color: #3399ff;
color: white;
width: 60%;
margin: auto;
}

#header p
{
display: inline;
}

Answer

margin: auto will not work on a fixed (or absolute) position div. Instead you need to set left: 50% and the left margin to negative half of the element width.

#header 
{
    position: fixed;
    width: 60%;
    left: 50%;
    margin-left: -30%;
}

http://jsfiddle.net/ZAqJM/

UPDATE: as of now most browsers will support transfrom: translate so you can comfortably do:

{
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
}