CSS使用自动保证金固定头寸

ber*_*rdw 18 css

我想要一个保持页面水平中心的组件(两列),我有一个子组件(右列),我希望它的位置是固定的,所以子组件的位置是固定的,但整体两列要居中.

#content {
    width: 1200px;
    height:auto !important;
    height:100%;
    min-height:100%;
    padding-top: 42px;
    padding-bottom: 100px;
    margin-auto: 0 auto;
    position: relative;
}

#left {
    width: 700px;
    float: left;
}

#right {
        width: 500px;
        position: fixed;
        top: 0px;
}
Run Code Online (Sandbox Code Playgroud)

pst*_*trm 59

您可以使用margin: 0 autoposition: fixed如果设置leftright.

.wrapper {
    position:fixed;
    top: 0;
    left: 0;
    right: 0;
    width: 500px;
    margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)

这也适用于position: absolute;和垂直.

演示:http://codepen.io/pstenstrm/pen/myaWVJ

  • @bernardw我建议接受这个答案;) (3认同)

Gav*_*imo 35

你不能这样做margin:auto,但你可以做这样的事情:

#CSS-SELECTOR-YOU-ARE-USING{
    background:#FF0000; // Just so you can see whats going on
    position:fixed; // Position the element
    right:50%; // Move it to the right for 50% of parent element
    margin-right:-250px; // You need here to put 1/2 of what you have below in width
    width:500px;
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以将元素向右移动50%,然后将其向后移动一半宽度.这样你就可以获得居中元素position:fixed.

  • 如果您有固定宽度,则此答案是正确的。对于流体宽度(即 100%),请考虑下面显示的 pstenstrm 的答案“您可以使用 margin: 0 auto with position: fixed if you set left and right.”。 (3认同)
  • 等待 !如果你有其他元素带有 `margin: auto` 和 `position: relative`,当你尝试调整浏览器的宽度时,你会发现这两个图层没有正确对齐。这是 CSS 的一个常见错误。 (2认同)