Centering a div using flex and position: absolute gives different results on Safari [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

This question already has an answer here:

I am looking for an explanation why the following code works differently in Chrome and Safari

Chrome centers the inner item both vertically and horizontally, whereas Safari doesn't.

.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>

Here is a codepen link: https://codepen.io/anon/pen/bRyQLx

回答1:

That is because Safari doesn't treat absolute positioned elements as the rest of the browsers do.

To center an absolute positioned element in Safari you need to use transform: translate

Note, if it should be relative to its parent, the flex-container, the flex-container has to have a position other than static, so here I gave it 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>


回答2:

It sounds like your version of Safari may not be recognizing display: flex.

Older versions of Safari may provide spotty support for flexbox, and full support was not offered until version 10.1 (released March 2017).

Try replacing display: flex; with the following:

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

Here's a codepen that you can use to test with your version of Safari.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!