219
#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) から離れている必要があり、すべてのブラウザー サイズでページの中央に水平方向に配置する必要があり、ページの残りの部分をスクロールするときに移動しないようにする必要があります。

それは可能ですか?

4

8 に答える 8

168
left: 50%;
margin-left: -400px; /* Half of the width */
于 2010-07-01T11:45:04.020 に答える
60

インラインブロックを使用するオプションがある場合は、次のアプローチをお勧めします。

.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-horizo​​ntally-centered.html

于 2012-04-27T14:28:52.950 に答える
37

2016 年 9 月の編集: 世界が動いたので、これに対して時折の賛成票を得るのはまだ良いことですが、今は変換を使用する (そして賛成票がたくさんある) 回答を使用します。私はもうこのようにはしません。

マージンを計算したり、サブコンテナーを必要としない別の方法:

#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) */
}
于 2014-02-27T15:32:37.037 に答える
7

別の 2 div ソリューションを次に示します。簡潔に保ち、ハードコーディングしないようにしました。まず、予想される html:

<div id="outer">
  <div id="inner">
    content
  </div>
</div>

次の css の背後にある原則は、「外側」のいずれかの側を配置し、「内側」のサイズを想定しているという事実を使用して、後者を相対的にシフトすることです。

#outer {
  position: fixed;
  left: 50%;          // % of window
}
#inner {
  position: relative;
  left: -50%;         // % of outer (which auto-matches inner width)
}

このアプローチは Quentin のアプローチに似ていますが、inner は可変サイズにすることができます。

于 2014-07-17T17:54:30.640 に答える
5

... または、メニュー div を別の 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;
    }
于 2010-07-01T11:49:37.300 に答える