【问题标题】:How to horizontally center a fixed positioned element如何水平居中固定定位的元素
【发布时间】:2014-02-06 12:43:53
【问题描述】:

我有一个图层,里面有一张图片:

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

它是固定位置的:

#foo {
    position: fixed;
}

但我也希望图层在页面中水平居中。所以我试过: http://jsfiddle.net/2BG9X/

#foo {
    position: fixed;
    margin: auto
}

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

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

但不起作用。知道如何实现它吗?

【问题讨论】:

  • 尝试使用margin:0 auto;
  • left: 50%; margin-left: -halfofyourdivsize;.
  • @Zzyrk 您不能将margin: auto; 应用于固定元素。

标签: html css css-position


【解决方案1】:

当您将一个元素定位到fixed 时,它会脱离文档流,即使margin: auto; 也不起作用,如果您愿意,可以在该fixed 定位元素中嵌套一个元素,然后使用@987654327 @为此。

Demo

Demo 2 (在body 元素中添加了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;
}

有些人会建议您将 display: inline-block; 用于子元素,而父元素设置为 text-align: center;,如果这足以满足您的需求,那么您也可以这样做...

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

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

Demo 2

只要确保子元素使用text-align: left;,否则它将继承父元素的text-align

【讨论】:

    【解决方案2】:

    使用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 更好。
    • 不客气,反正它们是两种完全不同的解决方案,各有利弊。
    【解决方案3】:

    试试下面的。

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

    Fiddle

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2011-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-15
        • 2011-01-01
        • 2021-01-10
        • 1970-01-01
        相关资源
        最近更新 更多