使用 flex 和 position: absolute 在 Safari 上居中 div 会给出不同的结果



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

Chrome 将内部项目垂直和水平居中,而 Safari 则不会。

.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;
}
<div class='container'>
<div class='flex-container'>
<div class='flex-overlapping-item'>
<h3>Drag photo here</h3>
<p>Photo must have 1000px x 1000px</p>
</div>
<div class='flex-overlapping-item drag-zone'>
<div class='drag-zone-content'>
</div>
</div>
</div>
</div>

这是一个代码笔链接:https://codepen.io/anon/pen/bRyQLx

这是因为 Safari 不像其他浏览器那样处理绝对定位的元素。

  • Flexbox为绝对定位儿童提供新行为(自2016年起(
  • 弹性盒 - 绝对定位的弹性儿童

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

请注意,如果它应该相对于它的父级,flex-containerflex-container必须具有static以外的位置,所以在这里我给了它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  */
}
<div class='container'>
<div class='flex-container'>
<div class='flex-overlapping-item'>
<h3>Drag photo here</h3>
<p>Photo must have 1000px x 1000px</p>
</div>
<div class='flex-overlapping-item drag-zone'>
<div class='drag-zone-content'>
</div>
</div>
</div>
</div>

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

旧版本的 Safari 可能会提供对 flexbox 的不稳定支持,直到版本 10.1(2017 年 3 月发布(才提供全面支持。

尝试将display: flex;替换为以下内容:

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

下面是一个代码笔,可用于测试您的 Safari 版本。

最新更新