3

I'm learning CSS and looking at this example:

https://www.w3schools.com/css/tryit.asp?filename=trycss_image_text_center

I don't understand why when I remove "position:relative" for the parent div, it effects the text inside.

As I understand position relative makes the html element you apply it to be positioned relative to it's original. But here they haven't set any properties except position relative so why is it needed?

2
  • 2
    Give this a read:Absolute Positioning Inside Relative Positioning Commented Jun 18, 2018 at 20:53
  • 1
    The text is nested in an absolute positioned div (.center), with a top set to 50% of parent height (set by the img). In this case, it refers to the relative element (.container). If you remove relative property, the top property refers to top level element of the page, which actually is the body, so top:50% of the page itself, not the .container element. Commented Jun 18, 2018 at 20:54

3 Answers 3

3

Because, the position of the center div is absolute with left: 0 and top: 50% of the whole screen, unless you put it inside a parent with a relative position, it becomes left: 0 and top: 50% of that parent

Sign up to request clarification or add additional context in comments.

Comments

0

.container div is the first parent of .center div the second parent is the body tag then the html tag. the tag that has relative position becomes the parent of .center div who has position absolute.

Comments

-1

the relative position will let the text position according to its parent element. in order to position it with respect to the parent div or element in this case it is image. you need it to be positioned relative by that css tag position with value as relative.

1 Comment

Quite not clear. Besides, the image is not a parent here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.