本文翻译自:CSS Child vs Descendant selectors
I am a bit confused between these 2 selectors. 我对这两个选择器有些困惑。
Does the descendent selector: 后代选择器是否:
div p
select all p
within a div
whether or not it's an immediate descedent? 选择div
所有p
是否直接依赖? So if the p
is inside another div
it will still be selected? 因此,如果p
在另一个div
,它将仍然被选中?
Then the child selector: 然后是子选择器:
div > p
Whats the difference? 有什么不同? Does a child mean immediate child? 一个孩子意味着直系孩子吗? Eg. 例如。
<div><p>
vs 与
<div><div><p>
will both be selected, or not? 是否都会被选中?
#1楼
参考:https://stackoom.com/question/4xXZ/CSS子代与子代选择器
#2楼
Yes, you are correct. 是的,你是对的。 div p
will match the following example, but div > p
will not. div p
将与以下示例匹配,但div > p
将不匹配。
<div><table><tr><td><p> <!...
The first one is called descendant selector and the second one is called child selector . 第一个称为子代选择器 ,第二个称为子选择器 。
#3楼
Just think of what the words "child" and "descendant" mean in English: 只要想一想英语中的“孩子”和“后代”是什么意思:
- My daughter is both my child and my descendant 我的女儿既是我的孩子,又是我的后代
- My granddaughter is not my child, but she is my descendant. 我的孙女不是我的孩子,但她是我的后代。
#4楼
请注意,Internet Explorer 6不支持子选择器。(如果您在jQuery / Prototype / YUI等选择器中使用选择器,而不是在样式表中使用它,则该选择器仍然可以使用)
#5楼
Bascailly, " ab " selects all b's inside a, while " a>b " selects b's what are only children to the a , it will not select b what is child of b what is child of a . Bascailly,“AB”所有选择B的内部,而“A> B”选择B的东西只是孩子的一个 ,它不会的选择B什么是B的孩子是什么的孩子。
This example illustrates the difference: 此示例说明了不同之处:
div span{background:red}
div>span{background:green}
<div><span>abc</span><span>def<span>ghi</span></span></div>
Background color of abc and def will be green, but ghi will have red background color. abc和def的背景色将是绿色,但是ghi将具有红色的背景色。
IMPORTANT: If you change order of the rules to: 重要说明:如果您将规则的顺序更改为:
div>span{background:green}
div span{background:red}
All letters will have red background, because descendant selector selects child's too. 所有字母都将具有红色背景,因为子代选择器也会选择子字母。
#6楼
div p
Selects all 'p' elements where the parent is a 'div' element 选择所有父元素为“ div”元素的“ p”元素
div > p
It means immediate children Selects all 'p' elements where the parent is a 'div' element 这意味着直系子级会选择所有“ p”个元素,其中父级是“ div”元素