Short answer: no.
(简短的回答: 不。)
(It is now possible with CSS transform. See the edit below) ((现在可以使用CSS转换。请参见下面的编辑))
Long answer: The problem with using "fixed" positioning is that it takes the element out of flow .
(长答案:使用“固定”定位的问题是它会使元素脱离流动 。)
thus it can't be re-positioned relative to its parent because it's as if it didn't have one. (因此无法相对于其父对象重新定位,因为好像没有父对象一样。)
If, however, the container is of a fixed, known width, you can use something like: (但是,如果容器的宽度是已知的固定宽度,则可以使用以下方法:)
#fixedContainer {
position: fixed;
width: 600px;
height: 200px;
left: 50%;
top: 0%;
margin-left: -300px; /*half the width*/
}
http://jsfiddle.net/HFjU6/1/
(http://jsfiddle.net/HFjU6/1/)
Edit (03/2015): (编辑(03/2015):)
This is outdated information.
(这是过时的信息。)
It is now possible to center content of an dynamic size (horizontally and vertically) with the help of the magic of CSS3 transform. (现在,借助CSS3转换的魔力,可以将动态大小的内容(水平和垂直)居中。)
The same principle applies, but instead of using margin to offset your container, you can use translateX(-50%)
. (遵循相同的原则,但是可以使用translateX(-50%)
而不是使用margin来偏移容器。)
This doesn't work with the above margin trick because you don't know how much to offset it unless the width is fixed and you can't use relative values (like 50%
) because it will be relative to the parent and not the element it's applied to. (这不适用于上面的边距技巧,因为除非宽度固定,否则您不知道要偏移多少,并且您不能使用相对值(如50%
),因为它将相对于父对象而不是相对于父对象。应用于的元素。)
transform
behaves differently. (transform
行为有所不同。)
Its values are relative to the element they are applied to. (其值相对于它们所应用的元素。)
Thus, 50%
for transform
means half the width of the element, while 50%
for margin is half of the parent's width. (因此, transform
50%
表示元素宽度的一半,而空白的50%
则是父元素宽度的一半。)
This is an IE9+ solution (这是IE9 +解决方案)
Using similar code to the above example, I recreated the same scenario using completely dynamic width and height:
(使用与以上示例类似的代码,我使用完全动态的宽度和高度重新创建了相同的场景:)
.fixedContainer {
background-color:#ddd;
position: fixed;
padding: 2em;
left: 50%;
top: 0%;
transform: translateX(-50%);
}
If you want it to be centered, you can do that too:
(如果您希望它居中,也可以这样做:)
.fixedContainer {
background-color:#ddd;
position: fixed;
padding: 2em;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Demos: (演示:)
jsFiddle: Centered horizontally only
(jsFiddle:仅水平居中)
jsFiddle: Centered both horizontally and vertically
(jsFiddle:水平和垂直居中)
Original credit goes to user aaronk6 for pointing it out to me in this answer
(原始功劳归用户aaronk6在此答案中向我指出)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…