jklevin
jklevin

Reputation: 43

Flexbox justify-content: center not working properly in Safari

I'm having trouble getting flexbox and justify-content: center to play nicely in Safari.

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;
}

In Chrome and FF this gives a simple grey well, with a label centered above it. In Safari however the label does not center. Open the CodePen example below in Safari to see the uncentered label:

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

My hunch is that this is due to an implementation bug in Safari, but curious if anyone knows of an existing workaround.

Upvotes: 4

Views: 5550

Answers (1)

Michael Coker
Michael Coker

Reputation: 53664

absolute positioning is not formally supported by flexbox, though it may work in some browsers.

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

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

If you want it horizontally centered, just add a left and use transform: translate() to move it back 50% of it's own width, and you can use that to move it up 8px, too.

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

Upvotes: 3

Related Questions