The CSS cascade
Derek Bridge
Department of Computer Science,
University College Cork
The CSS cascade
Aims:
- to understand the idea of inheritance in CSS
- to know what a rule conflict is in CSS
- to understand the cascade in CSS
Inheritance
- Many CSS properties (but not all) are inherited
inheritance in CSS
a property applied to an element is also automatically applied to the
element's descendants
Over-riding inheritance
- The inheritance of a property is blocked if some other CSS rule specifies a value
for that property
- Class exercise: What colour will "I like the…family" be? What colour will
"Vombatus ursinus" be?
Resolving conflicts: importance and origin
- CSS has a well-defined way of deciding which of several conflicting rules will 'win'
- A full treatment of this would begin by discussing rule importance and rule
origin
- We'll look at these two briefly — but you don't need to learn these two
Resolving conflicts: importance
Resolving conflicts: origin
- Stylesheets have different origins
- author stylesheets
- user stylesheets
- the browser's default stylesheet
- If two rules conflict, the following is the order of precedence:
!important
rules from user stylesheets
!important
rules from author stylesheets
- other rules from author stylesheets
- other rules from user stylesheets
- the browser's default stylesheet
Resolving conflicts: specificity
- Some selectors are more specific than others
- Roughly(!), selecting by id is the most specific, then selecting by class
- Then, a selector with more children/descendants is more specific
- If two rules conflict, the more specific wins
Resolving conflicts: specificity
Class exercise: Which is the more specific in each
of these pairs of rules
i
{
color: blue;
}
.cocktail
{
color: green;
}
nav li
{
color: yellow;
}
li
{
color: gray;
}
#instructions b
{
color: teal;
}
ol li b
{
color: purple;
}
Resolving conflicts: ordering
Resolving conflicts: the cascade
- Note the way that the conflict resolution cascades:
- importance/origin
- specificity
- order
and when rules select an element, they beat inheritance
Class exercise
In the Instructions section of mojitos.html,
what colour will the word "crush" be and what colour will the rest
of that list item be?
#instructions
{
color: green;
}
li > b
{
color: red;
}
section b
{
color: blue;
}
section
{
color: yellow;
}
Conflicts are not irrelevant, just because they're difficult!