Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 428
user2209563 Avatar asked Mar 26 '13 00:03

user2209563


1 Answers

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%);
}
like image 172
Explosion Pills Avatar answered Oct 11 '22 07:10

Explosion Pills