0

I have a basic HTML structure here. The rule div > p selects the <p> element directly inside the <div>, which is expected. But it also selects the <p> element inside another <p> that itself is inside the <div>. I can't figure out the logic here.

HTML:

<div>
  <p>
    P#1, in the div.
    <p>P#2, in the P that's in the div.</p>
  </p>
</div>

CSS:

div > p {
  background-color: yellow;
}
Y MK
  • 11
  • 1
  • 2
  • 3
    This is because the browser thinks that nested `

    ` tags in the text input are invalid HTML5, and "auto-corrects" them into non-nested `

    ` tags. You can confirm it by using the inspector (actually there are 3 `p` elements in the browser output, the third one has no content). The resulting outerHTML of the div element is like `"

    \n

    \n P#1, in the div.\n

    P#2, in the P that's in the div.

    \n

    \n
    "`. It automatically closes the first `p` tag before opening the second `p` tag. And finally when the last `` is reached, there is no open `p`, thus the empty `p`
    – qrsngky Feb 20 '23 at 03:31
  • 1
    Also: https://stackoverflow.com/questions/12015804/nesting-p-wont-work-while-nesting-div-will (nesting p won't work even though nesting div works) Another thing you shouldn't do is trying to nest `
    ` within a `

    `: https://stackoverflow.com/questions/44835895/div-nested-in-p?noredirect=1&lq=1

    – qrsngky Feb 20 '23 at 03:35
  • Thank you. It seems my understanding of HTML is also lacking. It auto closes the first P tag which means the "nested" P is now a direct children also. – Y MK Feb 20 '23 at 03:59

0 Answers0