不理解CSS中的通用兄弟组合器(~)

huangapple go评论56阅读模式
英文:

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?

div1

div2
div3

div4
div5

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

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

英文:

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?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;style&gt;
    div ~ div{
        color: red;
    }
&lt;/style&gt;
&lt;div id=&quot;div1&quot;&gt;
    div1
    &lt;div id=&quot;div2&quot;&gt;div2&lt;/div&gt;
    &lt;div id=&quot;div3&quot;&gt;
        div3
        &lt;div id=&quot;div4&quot;&gt;div4&lt;/div&gt;
        &lt;div id=&quot;div5&quot;&gt;div5&lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

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?

答案1

得分: 2

这是关于CSS的内容,不需要进行翻译。

英文:

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:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

#div3{
  color: red;             /*inherited .. applied also to descendants*/
  border: solid 1px blue; /*not inherited .. applies only to selected elements*/
}

<!-- language: lang-html -->

&lt;div id=&quot;div1&quot;&gt;
  div1
  &lt;div id=&quot;div2&quot;&gt;div2&lt;/div&gt;
  &lt;div id=&quot;div3&quot;&gt;
    div3
    &lt;div id=&quot;div4&quot;&gt;div4&lt;span&gt;[span further descendant]&lt;/span&gt;&lt;/div&gt;
    &lt;div id=&quot;div5&quot;&gt;div5&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 16:19:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定