CSS 固定位置与自动边距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3232514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS Fixed position with Auto Margin
提问by bernardw
I want a component that keeps horizontal center of the page (two-columns), and I have a sub-component (right column) that I want its position to be fixed, so the sub-component's position to be fixed, but the whole two columns to be centered.
我想要一个保持页面水平中心(两列)的组件,我有一个子组件(右列),我希望它的位置是固定的,所以子组件的位置是固定的,但整个两列要居中。
#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;
}
回答by pstenstrm
You can use margin: 0 auto
with position: fixed
if you set left
and right
.
如果设置和margin: 0 auto
,position: fixed
则可以使用with 。left
right
.wrapper {
position:fixed;
top: 0;
left: 0;
right: 0;
width: 500px;
margin: 0 auto;
}
This also works with position: absolute;
and vertically.
这也适用于position: absolute;
和垂直。
回答by Gavrisimo
You cant do that with margin:auto
, but you can do something like this:
你不能用 来做到这一点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;
}
This way you move element to the right for 50%, and then move it back for half of its width. That way you get centered element with position:fixed
.
通过这种方式,您将元素向右移动 50%,然后将其向后移动其宽度的一半。这样你就可以使用position:fixed
.
回答by Cameron Drake
I like to use a wrapper as asolution for this problem:
我喜欢使用包装器来解决这个问题:
.wrapper {
position: fixed;
width: 100%;
top: 0px;
}
.wrapper .right {
width: 500px;
margin: auto;
}