Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

html - 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, forward-thinking method is to use Flexbox and absolute positioning of the text:

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

.text {
  position: absolute;
}
<div class='container'>
  <div class='text'>
    This should be centered
  </div>
  <img src="https://placehold.it/250x250" />
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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%);
}
<div class='container'>
  <div class='text'>
    This should be centered
  </div>
  <img src="https://placehold.it/250x250"/>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...