What are the different usages for the #, ., and > symbols and what do they reference?
For example, I know these two:
div#id {} // <div id="id" />
div.class {} // <div class="class" />
However, there are others which I don’t understand:
div#id element
div#id>element
div#id.class
div#id .class
div#id>element#id .class
Any insights?
As pst says, you should really read up more on your own. I’ll add that you can experiment using Firebug or an online tool like jsFiddle to see live results. But I understand not everyone combines ID and class selectors, and the fact that your selectors are so similar and bunched like that can be confusing, so here goes:
The
>symbol is called the child combinator, and is different from whitespace (the descendant combinator) in that>only looks one level deep in the DOM hierarchy.Compare the first two selectors:
Would match either of these:
Will only match this:
But not this because there is an intermediate
div.classoccurring betweenelementanddiv#id:Because the space represents the descendant combinator, it’s significant in CSS selector syntax (except when used between other combinators and simple selectors, e.g.
E > FandE>Fare the same).Compare the next two selectors:
By omitting the space, you are chaining three things together:
The element selector (
div),The ID selector (
#id), andThe class selector (
.class).Thus a single element must satisfy all three selectors in order to be targeted by its rule. In HTML, this means it has to have both attributes, like so:
<div id="id" class="class">Notice the whitespace separating
div#idand.class. This means.classapplies to a totally different element.Would match either of these:
But nothing here will be matched because there’s no
.classto look for withindiv#id:And not this either, for the same reason:
The last selector just involves putting it all together:
Funnily enough, the corresponding HTML structure would be invalid because you can’t have more than one element with the same ID, but anyway: