views:

229

answers:

3

What do these two CSS selectors mean?

h1#myItemOne h2
{
    background:#0099FF;
    color: #A3F4A3;
}

h1.myItemTwo  h2
{ 
    background:#0099FF;
    color: #A3F4A3;
}

Are these two selectors valid for use?

+7  A: 

The first matches an h2 element that is a child descendant of an h1 element with the id myItemOne

Example:

<h1 id="myItemOne">
    <h2>Me!</h2>
</h2>

The second matches an h2 element that is a child descendant of an h1 element with the class myItemTwo

Example:

<h1 class="myItemTwo">
    <h2>Me!</h2>
</h2>

They are both valid. The major difference is that id should be unique. Class does not have this requirement.

Reference: http://www.w3.org/TR/CSS2/selector.html

Ed Marty
Where you say "child" I believe you mean "descendant". h2 doesn't need to be a direct child in either selector. If you do want direct child then use something like "h1.myItemTwo > h2".
Laurence Gonsalves
Nice addition about the difference in child and descendant Laurence. Just to add, I don't think the child selector > is supported in IE6 and below, possibly some other older browsers too.
Pricey
+1  A: 
h1#myItemOne h2 { background:#0099FF; color: #A3F4A3; }

Means any h2 that is a descendant of an h1 element with ID equal to "myItemOne"

h1.myItemTwo h2 { background:#0099FF; color: #A3F4A3; }

Means any h2 that is a descendant of an h1 element with class equal to "myItemOne"

jitter
A: 

"#" defines a unique id in a page, the dot defines a class that you can use on several places.

Usage:

<h1 id="...."></h1>
<h1 class="...."></h1>
jeroen