What's the difference between
tag.class
and tag .class
or
tag#id
and tag #id
?
What's the difference between
tag.class
and tag .class
or
tag#id
and tag #id
?
tag.class
matches all elements with name tag
and with the class class
, e.g.:
div.foo { color: red; }
matches<div class="foo">
tag .class
matches all .class
elements that are descendants of tag
elements (note the space between tag
and .class
):
(Remember that "descendants" includes all children, their children, and so on - whereas, in comparison, the >
(child selector) only selects immediate children and not any grandchildren.)
div .foo { color: red; }
matches the<span>
in<div><p><span class="foo">
tag#id
and tag #id
are similar to the above, except matching on the id
attribute instead of the class
attribute[1]
div#foo { color: red; }
matches<div id="foo">
div #foo { color: red; }
matches the<span>
in<div><p><span id="foo">
Remember that because id=""
attributes are meant to be unique that additional selectors may be superfluous, e.g. div#bar
could be simplified to just #bar
(unless you're reusing the same CSS rules on different pages where #bar
may have different element tag names).
[1]: This is true in HTML, in other SGML and XML languages using CSS the .class
and #id
selectors can be mapped to other attribute names.
tag.class
would mean a tag
with class='class'
. Something like this:
<!-- This tag would be selected -->
<tag class="class">
...
</tag>
tag .class
would mean an element whose class='class'
, and is a descendant of a <tag>
. Something like this:
<tag>
...
<!-- This div would be selected -->
<div class="class">
</div>
...
</tag>
In general, something like selector1 selector2
would mean an element that matches selector2
and is a descendant of an element that matches selector1
. Consider this example:
CSS:
/*
div.face matches a div with class="face"
div.eye#left matches a div with class="eye" and id="left"
Hence, this would select an element with class="eye" and id="left" which is
inside a div with class="face"
*/
div.face div.eye#left {
}
HTML:
<div class="face"> <!-- div.face -->
<div class="upper">
<div class="eye" id="left"></div> <!-- div.eye#left is selected -->
<div class="eye" id="right"></div>
</div>
</div>
Space () is a descendant selector, see documentation: http://www.w3.org/TR/CSS2/selector.html#descendant-selectors
Long story short tag.class
applies to a tag
element with class class
, whereas tag .class
applies to any elements with class
class that are within tag
element.