Flexbox的justify-content:center在Safari中无法正常工作

4

我遇到了问题,无法让Safari浏览器正常使用flexbox和justify-content:center

HTML:

<div class="flex-row">
  <div class="label"> Label </div>
  <div class="well"></div>
</div>

CSS:

.flex-row {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.well {
  width: 230px;
  height: 200px;
  background-color: grey;
}

.label {
  z-index: 2;
  position: absolute;
  margin-top: -8px;
}

在Chrome和FF中,这将提供一个简单的灰色框,并在其上方居中显示标签。然而,在Safari中,标签没有居中。在Safari中打开下面的CodePen示例以查看未居中的标签:

https://codepen.io/jklevin/pen/weLvxx

我的直觉是这是Safari中的实现错误,但我想知道是否有任何现有的解决方法。

相关:https://dev59.com/aVwY5IYBdhLWcg3wHkuK - Michael Benjamin
1个回答

3

absolute 定位在 flexbox 中没有得到正式支持,虽然在某些浏览器中可能会起作用。

https://www.w3.org/TR/css-flexbox-1/#abspos-items

由于它不在流程之内,flex 容器的绝对定位子元素不参与 flex 布局。

如果您想要水平居中,只需添加一个 left 并使用 transform: translate() 将其移回其自身宽度的 50%,您也可以使用这个来将其向上移动 8px。

.flex-row {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.well {
  width: 230px;
  height: 200px;
  background-color: grey;
}

.label {
  z-index: 2;
  position: absolute;
  left: 50%;
  transform: translate(-50%,-8px);
}
<div class="flex-row">
  <div class="label"> Label </div>
  <div class="well"></div>
</div>
    


谢谢!完美运行。 - jklevin
实际上,如果这是页面上唯一的元素,那么它非常有效,但如果我想将其构建为一个独立的可重用组件,并在单行中有多个组件怎么办?使用 left: 50% 将意味着井的行中的所有标签将堆叠在一起。请参见:https://codepen.io/jklevin/pen/weLvxx - jklevin
@jklevin 不用谢。有很多种方法可以做到这一点,我会像这样做 https://codepen.io/mcoker/pen/Kqjwxz - Michael Coker
没错,谢谢你的帮助! - jklevin

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