0

Why, in the case of using the <p> tag, sibling combinators are applied to an element that does not have a common parent.

Here the style is applied to the and the text of the child block turns red :

div~div {
color: red;
}
<div>Блок 1</div>       
<p>Paragraph 1
    <div>Child Block 1</div>
</p>

Here the style is not applied and the text inside the div does not turn red:

div~div {
color: red;
}
<div>Блок 1</div>       
<section>Section 1
    <div>Child Block 1</div>
</section> 

Does <p> have some hidden property or is there an invisible common parent of <div> blocks?

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
Kolenbass
  • 13
  • 3
  • 2
    The `

    ` element is automatically closed by the `

    ` start tag, so the `
    ` elements _do_ have a common parent. Using a [validator](https://validator.w3.org/nu/) would point out the mistake.
    – Alohci May 15 '23 at 20:57
  • Thanks for the reply. Now I have read the definition of the

    element from the reference book again and realized that I did not attach importance to the phrase "If there is no closing tag, it is assumed that the end of the paragraph coincides with the beginning of the next paragraph or other block element"

    – Kolenbass May 15 '23 at 21:01

1 Answers1

0

There is nothing wrong here. It is a behavior of p element.

Paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing p tag

So if you place any other element inside p element, then p element automatically close. In your code, because of automatically close, the html that render on browser is:-

<div>Блок 1</div>       
<p>Paragraph 1</p>
<div>Child Block 1</div>
<p></p>

And as you are using General Sibling Selector in CSS so in this p element case second div is sibling to first div. And that's why CSS is applying to second div.

While in section element case, section element doesn't close automatically, if you place any other elements inside it. So, in section element case, the html render on browser is:-

<div>Блок 1</div>       
<section>Paragraph 1
   <div>Child Block 1</div>
</section>

And, in this case, the second div is not sibling of first div. And that's why CSS is not applying on second div.

Developer
  • 1,297
  • 1
  • 4
  • 15