4

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.

Asons
  • 84,923
  • 12
  • 110
  • 165
jklevin
  • 43
  • 1
  • 3

1 Answers1

3

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>
    
Michael Coker
  • 52,626
  • 5
  • 64
  • 64
  • Thanks! Works perfectly. – jklevin Jul 18 '17 at 22:35
  • Actually, this works quite well if this is the only element on the page, but what if I wanted to build this Well as an independent reusable component, and have a number of them within a single row? Using `left: 50%` will mean all of the labels within a row of wells will stack. See: https://codepen.io/jklevin/pen/weLvxx – jklevin Jul 18 '17 at 22:49
  • @jklevin you're welcome. you can do that a bunch of ways, I would do it like this https://codepen.io/mcoker/pen/Kqjwxz – Michael Coker Jul 18 '17 at 22:56
  • Makes sense. Thanks for the help! – jklevin Jul 18 '17 at 23:15