0

What's the difference between

tag.class and tag .class

or

tag#id and tag #id?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Dominik Schmidt
  • 537
  • 1
  • 8
  • 22

3 Answers3

5

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.

Dai
  • 141,631
  • 28
  • 261
  • 374
2

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>
John Bupit
  • 10,406
  • 8
  • 39
  • 75
1

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.

Crozin
  • 43,890
  • 13
  • 88
  • 135