英文:
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?
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 -->
<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>
<!-- 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 -->
<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>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论