居中<div>而不使用"margin:auto;"

use*_*563 6 html css google-chrome

我正在寻找一种在Google Chrome浏览器页面中水平居中div的方法.

我尝试使用margin:auto; 但我已经读过谷歌浏览器不支持此功能.结果,我的div保持与屏幕左侧对齐.

如果我使用,例如,margin-left:100px; div确实移向页面的中心,但我不想手动居中.

HTML:

<body>
    <div id="header">
        <p>John Doe</p>
        <p>email</p>
    </div>   
</body>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

Exp*_*lls 11

margin: auto不适用于固定(或绝对)位置div.相反,您需要left: 50%将左边距设置为元素宽度的负半边.

#header 
{
    position: fixed;
    width: 60%;
    left: 50%;
    margin-left: -30%;
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/ZAqJM/

更新:截至目前,大多数浏览器都支持,transfrom: translate因此您可以轻松地做到:

{
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)