Let's add specificity to the class selector to allow us to target a specific element which has a specified class attached to it. We'll do this by applying contextual class selectors.
There are two different ways to use contextual class selectors. The general syntax for the two are:
element.className |
targets an element that has been assigned the class "className" |
.className element |
targets an element that is a descendant of any element that has been assigned the class of "className" |
We'll build upon the example we used for simple classes to demonstrate the application of contextual class selectors. The only change is the addition of two new rules which each apply in a very specific context.
Example Stylesheet
p { font-family: Verdana, sans-serif; }
.specialtext { font-weight: bold; }
p.specialtext { color: red; }
.specialtext span { font-style: italic; }
In the above style sheet, we have added a rule with the p.specialtext
contextual class selector. You would read this selector as 'any P tag that has
the
"specialtext"
class.'
The second additional rule has the .specialtext span
selector. This is read as 'any
SPAN tag that is a descendant of an element with the "specialtext"
class.'
Example Markup
The markup below should be familiar to you. It is the same markup that we used for the simple class selectors example.
<h3 class="specialtext">This is a heading with the same
class as the second paragraph.</h3>
<p>This paragraph has no class.</p>
<p class="specialtext">
When a tag is identified with a class, we can target
it <span>regardless</span> of its position in the
hierarchy.
</p>
This is a heading with the same class as the bottom paragraph.
This paragraph has no class.
When a tag is identified with a class, we can target it regardless of its position in the hierarchy.
The obvious effect is that the lower paragraph is now in red, and the text in the SPAN tag is blue.
What may not be obvious is that the heading and lower paragraph are still using the specialtext class. We know this because both are bold.
The addition of p.specialtext
means that the bottom paragraph still
uses the properties of the specialtext class (bold)
but now also uses the rule for p.specialtext
(red) which only
applies if the specialtext class is attached to a P tag. On top
of that, the .specialtext
span rule (italic) adds italic styling to the text in
the SPAN tag.
All rules that target an element will be applied to the element. The styles are applied in the order that they are listed, from the top, down.1
Footnotes
- This is a simplification of the second rule of the Cascade. The Cascade defines a set of rules which determine the precedence of rules whenever there is a conflict, based on criteria giving each rule an order and a 'weight'. We'll be discussing the Cascade next week. Until then, your understanding of the first rule of the Cascade will suffice for this week.