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

这可能吗?


当前回答

下面是一个flexbox的解决方案,当使用全屏包装div时。justify-content居中,它的子div水平和align-items垂直居中。

<div class="full-screen-wrapper">
    <div class="center"> //... content</div>
</div>

.full-screen-wrapper { 
  position: fixed;
  display: flex;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  top: 0;
  align-items: center;
}

.center {
  // your styles
}

其他回答

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

这里的答案已经过时了。现在您可以轻松地使用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包装在另一个:

    <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);
}

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

.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