HTML and CSS Reference
In-Depth Information
Combining Selectors
So far we've looked at how to use different types of selectors individually, but we also need
to know how to use these selectors together. By combining selectors we can be more spe-
cific about which element or group of elements we'd like to select.
For example, say we want to select all paragraph elements that reside within an element
with a class attribute value of hotdog and set their background color to brown . However,
if one of those paragraphs happens to have the class attribute value of mustard , we want
to set its background color to yellow . Our HTML and CSS may look like the following:
Click here to view code image
1. <div class="hotdog">
2. <p>...</p>
3. <p>...</p>
4. <p class="mustard">...</p>
5. </div>
1. .hotdog p {
2. background: brown;
3. }
4. .hotdog p.mustard {
5. background: yellow;
6. }
When selectors are combined they should be read from right to left. The selector farthest to
the right, directly before the opening curly bracket, is known as the key selector . The key
selector identifies exactly which element the styles will be applied to. Any selector to the
left of the key selector will serve as a prequalifier.
The first combined selector above, .hotdog p , includes two selectors: a class and a type
selector. These two selectors are separated by a single space. The key selector is a type se-
lector targeting paragraph elements. And because this type selector is prequalified with a
class selector of hotdog, the full combined selector will only select paragraph elements
that reside within an element with a class attribute value of hotdog .
The second selector above, .hotdog p.mustard , includes three selectors: two class
selectors and one type selector. The only difference between the second selector and the
first selector is the addition of the class selector of mustard to the end of the paragraph
type selector. Because the new class selector, mustard , falls all the way to the right of the
Search WWH ::

Custom Search