Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not understanding the General sibling combinator in CSS (~)

I’m learning different css selectors and with the example given people I don’t understand why div4 is selected. As the id div4 is not sibling to div3? Because to me it’s a child but maybe because it’s only divs I got it wrong or it’s the definition of sibling that is wrong?

<style>
    div ~ div{
        color: red;
    }
</style>
<div id="div1">
    div1
    <div id="div2">div2</div>
    <div id="div3">
        div3
        <div id="div4">div4</div>
        <div id="div5">div5</div>
    </div>
</div>

I would have expected only div3 as sibling of div2 and div5 as sibling of div4 to be selected.

So can anyone explain what I’m getting wrong or why is that that div4 is selected?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: (following answer)
The following code snippet shows the answer in action using general sibling combinator with a non inherited property

<style>
    div ~ div{
    border: solid 2px ;
}
</style>
<div id="div1">
    div1
    <div id="div2">div2</div>
    <div id="div3">
        div3
        <div id="div4">div4</div>
        <div id="div5">div5</div>
    </div>
</div>

>Solution :

It’s because the css color property is inherited from the parent.

https://developer.mozilla.org/en-US/docs/Web/CSS/color

Inherited yes

https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance

inherited properties, which by default are set to the computed value
of the parent element

So the scenario you are addressing is not striclty bound to the sibling selector per se.

You can see here that having that rule specifically addressing the #div3 will set that property to all its children as inherited:

#div3{
  color: red;             /*inherited .. applied also to descendants*/
  border: solid 1px blue; /*not inherited .. applies only to selected elements*/
}
<div id="div1">
  div1
  <div id="div2">div2</div>
  <div id="div3">
    div3
    <div id="div4">div4<span>[span further descendant]</span></div>
    <div id="div5">div5</div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading