#menu {
    position: fixed;
    width: 800px;
    background: rgb(255, 255, 255); /* The Fallback */
    background: rgba(255, 255, 255, 0.8);
    margin-top: 30px;
}

我知道这个问题有一百万次了,但是我找不到答案。 我有一个div,它应该是固定在屏幕上,即使页面是滚动的,它应该始终保持在屏幕中间的中心!

div的宽度应该是500px,距离顶部应该是30px (margin-top),对于所有浏览器大小,应该水平居中在页面中间,当滚动页面的其余部分时不应该移动。

这可能吗?


当前回答

这里的答案已经过时了。现在您可以轻松地使用CSS3转换,而无需硬编码页边距。这适用于所有元素,包括没有宽度或动态宽度的元素。

水平中心:

left: 50%;
transform: translateX(-50%);

垂直中心:

top: 50%;
transform: translateY(-50%);

水平的和垂直的:

left: 50%;
top: 50%;
transform: translate(-50%, -50%);

兼容性不是问题:http://caniuse.com/#feat=transforms2d

其他回答

可以这样水平居中放置div:

html:

<div class="container">
    <div class="inner">content</div>
</div>

css:

.container {
    left: 0;
    right: 0;
    bottom: 0; /* or top: 0, or any needed value */
    position: fixed;
    z-index: 1000; /* or even higher to prevent guarantee overlapping */
}

.inner {
    max-width: 600px; /* just for example */
    margin: 0 auto;
}

使用这种方法,你将始终保持你的内部块居中,此外,它可以很容易地变成真正的响应(在这个例子中,它将只是在较小的屏幕上流动),因此在问题示例和选择的答案中没有限制。

left: 50%;
margin-left: -400px; /* Half of the width */

... 或者你可以把你的菜单div包装在另一个:

    <div id="wrapper">
       <div id="menu">
       </div>
    </div>


#wrapper{
         width:800px;
         background: rgba(255, 255, 255, 0.8);
         margin:30px auto;
         border:1px solid red;
    }

    #menu{
        position:fixed;
        border:1px solid green;
        width:300px;
        height:30px;
    }
div {
   left: calc((100vw - 100%) / 2);
}

编辑2016年9月:虽然偶尔还能得到点赞还是不错的,因为世界已经在发展了,我现在还是选择使用transform的答案(它有很多赞)。我不会再这样做了。

另一种不需要计算边距或子容器的方法:

#menu {
    position: fixed;   /* Take it out of the flow of the document */
    left: 0;           /* Left edge at left for now */
    right: 0;          /* Right edge at right for now, so full width */ 
    top: 30px;         /* Move it down from top of window */
    width: 500px;      /* Give it the desired width */ 
    margin: auto;      /* Center it */
    max-width: 100%;   /* Make it fit window if under 500px */ 
    z-index: 10000;    /* Whatever needed to force to front (1 might do) */
}