【问题标题】:How to center fixed content in flexbox container in Safari?如何在 Safari 的 flexbox 容器中居中固定内容?
【发布时间】:2018-01-14 18:21:53
【问题描述】:

Following code 在 Chrome 和 Firefox 中按预期工作(块居中),但在 Safari 中子容器略有偏离:

#container {
  width: 100%;
  background: yellow;
  height: 20px;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
}

#content {
   padding: 0px;
  background: linen;
  position: fixed;
} 

我的问题是 - 如何在 Safari 的“显示:flexbox”父级中居中“位置:固定”元素?

【问题讨论】:

    标签: css safari flexbox css-position


    【解决方案1】:

    带有position: fixed(或position: absolute)的元素在Safari 中的行为方式与在Chrome/Firefox 中的行为方式不同。

    要在 Safari 中居中弹性项目,您需要使用 transform: translate

    Updated codepen

    堆栈sn-p

    #container {
      width: 100%;
      background: yellow;
      height: 20px;
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      justify-content: center;
    }
    
    #content {
      padding: 0px;
      background: linen;
      position: fixed;
      left: 50%;
      transform: translateX(-50%);
    } 
    <div id="container">
      <div id="content">THIS CONTENT IS NOT CENTERED IN SAFARI</div>
    </div>

    【讨论】:

    • 是的,这看起来是最便宜的有效解决方案。我想知道为什么这在 Safari 和 Chrome 中有所不同 - 是故意的(比如以不同的方式解释某些 CSS 规范)还是只是一个错误。
    • @shabunc 这是对 Flexbox 模型所做的更改,其中一些浏览器还没有赶上。这是一个详尽的解释stackoverflow.com/questions/32991051/… ...这也可能是重复的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2019-02-04
    • 2016-09-10
    • 2019-07-22
    • 1970-01-01
    • 2021-11-06
    • 2016-12-18
    相关资源
    最近更新 更多