#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),对于所有浏览器大小,应该水平居中在页面中间,当滚动页面的其余部分时不应该移动。

这可能吗?


当前回答

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

其他回答

如果使用内联块是一个选项,我会推荐这种方法:

.container { 
    /* fixed position a zero-height full width container */
    position: fixed;
    top: 0; /* or whatever position is desired */
    left: 0;
    right: 0;
    height: 0;
    /* center all inline content */
    text-align: center;
}

.container > div {
    /* make the block inline */
    display: inline-block;
    /* reset container's center alignment */
    text-align: left;
} 

我在这里写了一篇简短的文章:http://salomvary.github.com/position-fixed-horizontally-centered.html

编辑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) */
}

这里的答案已经过时了。现在您可以轻松地使用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 {
   left: calc((100vw - 100%) / 2);
}

可以这样水平居中放置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;
}

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