使用flex和position来居中div:absolute在Safari上提供不同的结果

时间:2017-07-18 14:52:27

标签: css css3 safari flexbox

我正在寻找解释为什么以下代码在Chrome和Safari中的工作方式不同

Chrome会将内部项目纵向和横向居中,而Safari则不会。

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTicker) userInfo:nil repeats:YES];
.flex-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 300px;
  background: #e2e2f2;
}

.flex-overlapping-item {
  position: absolute;
  margin: auto;
}

以下是codepen链接:https://codepen.io/anon/pen/bRyQLx

2 个答案:

答案 0 :(得分:1)

这是因为Safari并没有像其他浏览器一样对待绝对定位元素。

要使Safari中的绝对定位元素居中,您需要使用transform: translate

注意,如果它应该是相对于其父级flex-containerflex-container必须有static以外的位置,那么我在这里给它{{ 1}}



position: relative;

.flex-container {
  position: relative;                /*  added  */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 300px;
  background: #e2e2f2;
}

.flex-overlapping-item {
  position: absolute;
  left: 50%;                         /*  added  */
  top: 50%;                          /*  added  */
  transform: translate(-50%,-50%);   /*  added  */
}




答案 1 :(得分:0)

听起来您的Safari版本可能无法识别display: flex

较早版本的Safari可能会为flexbox提供支持,并且在版本10。1(2017年3月发布)之前不会提供全面支持。

尝试使用以下内容替换display: flex;

display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

这是一个codepen,您可以使用它来测试您的Safari版本。