0

I'm trying to understand the purpose of using position: relative; to center text in a container.

Referencing this: How do i center text on an image? and using this as an example: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_image_text

Both of these have the overall container set to position: relative; and the text to position: absolute;

But neither explain why the greater container needs to be set to position: relative; (and in fact why the text must be set to absolute and not relative).

Surely it would make more sense if the only positioning information that existed to solve this centering problem was position: relative; on the text element. But doing this always fails to center text correctly in a container.

What's the logic here?

bitclip
  • 187
  • 7

1 Answers1

1

From the MDN docs on absolute position:

…positioned relative to its closest positioned ancestor…

position: absolute places an element at specific coordinates. Those coordinates need a positioning context. (50px from where?) Setting the container element to position: relative establishes the positioning context for its descendants.

ray
  • 26,557
  • 5
  • 28
  • 27