Skip to content Skip to sidebar Skip to footer

How To Center Absolutely Positioned Children Of A Flex Container In Safari?

I have a container that contains both an image, and some text. I want the text to be vertically and horizontally centered in the middle of the image. It seems that the easiest, for

Solution 1:

When it comes to Flexbox and absolute positioning, there is a few do's and don't's, and in this case, Safari won't center an absolute positioned element the other browsers does.

You can combine Flexbox and transform: translate, as the latter does not impact the former, and when times comes, where they all behave the same with Flexbox alone, you can just drop the transform/left/top part.

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}
<divclass='container'><divclass='text'>
    This should be centered
  </div><imgsrc="https://placehold.it/250x250"/></div>

Solution 2:

Respectfully, there are a few wrong assumptions in your question:

  • "Safari (wrong): [image]" - Safari is not necessarily wrong.
  • "All other browsers (correct): [image]" - The other browsers are not necessarily correct.
  • "I thought Flexbox was really ready for primetime.." - It is. 98% of browsers support flexbox.
  • "Centering content horizontally and vertically is something Flexbox should be great at." - It is.

Is there anything I'm missing here?

Yes, the part in the spec where it says that absolutely-positioned flex items ignore flex properties.

4.1. Absolutely-Positioned Flex Children

An absolutely-positioned child of a flex container does not participate in flex layout.

If some browsers choose to apply flex properties to absolutely-positioned flex items, that's their choice. But if a browser ignores flex properties on such elements, that doesn't necessarily mean they are in violation of the spec.

In reading the entire section in the spec, there doesn't appear to be a clear right or wrong.

For a more stable and reliable solution, don't use flex properties to position out-of-flow elements. Use CSS positioning properties instead:

Post a Comment for "How To Center Absolutely Positioned Children Of A Flex Container In Safari?"