2

Following code works as expected (block is centered) in Chrome and Firefox but in Safari child container is slightly off:

#container {
  width: 100%;
  background: yellow;
  height: 20px;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
}

#content {
   padding: 0px;
  background: linen;
  position: fixed;
} 

enter image description here enter image description here

My question would be - how to center "position: fixed" element in a "display: flexbox" parent in Safari?

Asons
  • 84,923
  • 12
  • 110
  • 165
shabunc
  • 23,119
  • 19
  • 77
  • 102

1 Answers1

3

Element with position: fixed (or position: absolute) won't behave in the same way in Safari as they do in Chrome/Firefox.

To center a flex item in Safari you need to use transform: translate

Updated codepen

Stack snippet

#container {
  width: 100%;
  background: yellow;
  height: 20px;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
}

#content {
  padding: 0px;
  background: linen;
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
} 
<div id="container">
  <div id="content">THIS CONTENT IS NOT CENTERED IN SAFARI</div>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165
  • yep, this looks like the cheapest valid solution. I wonder though why this differs in Safari and Chrome - is it intentional (like interpreting some CSS spec differently) or just a bug. – shabunc Aug 07 '17 at 16:01
  • 1
    @shabunc It is a changed made in the Flexbox model, where some browsers still haven't catch'd up yet. Here is a thorough explanation https://stackoverflow.com/questions/32991051/absolutely-positioned-flex-item-is-not-removed-from-normal-flow-in-firefox-ie1 ... which might as well qualify as a duplicate – Asons Aug 07 '17 at 16:17