1
<p>hello
    <div>test</div>
</p>

<div>yo
    <p>hi</p>
</div>

<p>hello</p>

I have the following code and when I use the following styles I get the following.

p + div {
    color:orange;
}

enter image description here

It styles the div inside the p, and I thought that it's only supposed to style siblings immediately after on the same level? What's weird is if I do the following

div + p {
     color:orange;
}

it does not style the p inside the div tag as shown.

enter image description here

Does anyone know what's going on?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Eli
  • 827
  • 1
  • 7
  • 21
  • 1
    the p inside the div inherits the yellow of the parent div that you have styled in the first example, in the second example, you only have the last p that immediately follows a div which is why only that one is styled. (as an aside, your div inside the p is invalid html) – Pete Jan 10 '22 at 11:08
  • 1
    @pete actually the aside explains the actual reason. – Salman A Jan 10 '22 at 11:16

2 Answers2

2

Your HTML markup is invalid. <div> cannot be placed inside <p> so the browser fixes the markup by changing this:

<p>hello
  <div>test</div>
</p>
<div>yo
  <p>hi</p>
</div>
<p>hello</p>

... into this:

<p>hello</p>
<div>test</div>
<p></p>
<div>yo
  <p>hi</p>
</div>
<p>hello</p>

Now p + div matches test and yo. And hi inherits the parent's color.

Salman A
  • 262,204
  • 82
  • 430
  • 521
2

Your code is broken when you put div inside p tag.

so <div>test</div> is considered as adjacent to p and applied orange color.

and <div>yo<p>hi</p> </div> is considered as adjacent to another p and applied orange color.

For more clarity, See the below DOM structure that has been created using above code.

enter image description here

Ezhilisai
  • 321
  • 3
  • 5