Centering a div using flex and position: absolute

2019-03-06 19:32发布

问题:

This question already has an answer here:

  • Absolutely positioning with flexbox in Safari 1 answer

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.

  • Flexbox Gets New Behavior for absolute-positioned Children (from 2016)
  • Flexbox - Absolutely-Positioned Flex Children

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.