Here are our culprits:
/* Child Selector */
div > span {
font-style: italic;
}
/* Descendant Selector */
div span {
color: red;
}
The best explanation I've read is to think of what these words mean in English:
- My son is my child, AND is my descendant
- My grandson is NOT my child, but IS my descendant
Let's take a look at the difference in syntax between these selectors. Below, we see that really the only difference is instead of using a space between our div and span (which is the typical "descendant" selector syntax), we will use a ">" symbol:
/* Child Selector */
div > span {
font-style: italic;
}
/* Descendant Selector */
div span {
color: red;
}
To try and describe in English, the ">" for child selection means: Match only my descendants (i.e. elements within a given node) that are my children (i.e. the immediate level below me), and ignore matches within my children. (e.g. Match MY son, but not HIS son).In my fiddle, I have a div with 4 immediate "children" (2 spans, 2 paragraphs); I also have a span within one of those paragraphs. In the above CSS, we see that I'm saying to color ALL span descendants of my parent (div) red, but style ONLY the children spans of my parent with italics. The result is like so:
In short, when considering descendant vs child, I consider my family to determine which things I want to actually select. Selection really depends on your intent; in some cases it will be safer to select only children to avoid applying your styles incorrectly to similar elements within those children. Have fun!
No comments:
Post a Comment