如何水平居中一个固定定位的元素

3

我有一个包含图像的层:

<div id="foo"><img src="url" /></div>

并且它是固定定位:

#foo {
    position: fixed;
}

但我也希望该层在页面中水平居中。因此,我尝试了以下方法:http://jsfiddle.net/2BG9X/

#foo {
    position: fixed;
    margin: auto
}

and http://jsfiddle.net/2BG9X/1/

#foo {
    position: fixed;
    left: auto;
}

但不起作用。有什么办法实现它吗?

尝试使用 margin:0 auto; - Zzyrk
左侧: 50%; 左边距: -你的div尺寸的一半; - putvande
@Zzyrk 你不能将 margin: auto; 应用于固定元素。 - Lars Beck
4个回答

9
当您将元素定位为fixed时,它会脱离文档流,即使使用margin:auto;也无效。如果需要,可以在该fixed定位元素内嵌一个元素,然后对其使用margin:auto;演示 演示2(添加了height以便您测试滚动) HTML
<div class="fixed">
    <div class="center"></div>
</div>

CSS

.fixed {
    position: fixed;
    width: 100%;
    height: 40px;
    background: tomato;
}

.center {
    width: 300px;
    margin: auto;
    height: 40px;
    background: blue;
}

有些人会建议您在父元素设置为text-align: center;的情况下,使用display: inline-block;对子元素进行样式设置,如果这可以满足您的需求,那么您也可以选择这种方法...

.fixed {
    position: fixed;
    width: 100%;
    height: 40px;
    background: tomato;
    text-align: center;
}

.center {
    display: inline-block;
    width: 300px;
    height: 40px;
    background: blue;
}

示例 2

请确保在子元素中使用text-align: left;, 否则它将继承父元素的text-align设置。


1

请尝试以下方法。

#foo {
    position: fixed;
    left: 50%;
    width: 30%;
    transform: translate(-50%, 0);
}

小提琴


1

请使用transform: translate(-50%, 0);
示例代码: http://codepen.io/fcalderan/pen/uJkrE

CSS

div {
  position: fixed;
  border: 3px #555 solid;
  left: 50%;
  -webkit-transform: translate(-50%, 0);
  -moz-transform: translate(-50%, 0);
  -ms-transform: translate(-50%, 0);
  transform: translate(-50%, 0);
}

谢谢。是个不错的选择,但是@Mr.Alien的更好。 - Manolo
不客气,无论如何它们都是两种完全不同的解决方案,各有优缺点。 - Fabrizio Calderan

0

这种方式不是跨浏览器的,你必须为图层设置百分比宽度,例如 width:30%,并设置 left:35%right:35%position:fixed
这样更好,并且适用于所有浏览器的 RTL 和 LTR。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接