Understand which CSS rule wins
What you will learn
- Attach an external stylesheet.
- Predict simple cascade conflicts and inheritance.
Create styles.css next to index.html and add <link rel="stylesheet" href="styles.css"> inside head. HTML loads the stylesheet through that path. Keep the filename in the link and on disk identical. The downloaded examples already contain this connection.
A CSS rule combines a selector and declarations. In .intro { color: navy; }, the selector matches elements whose class contains intro; color is the property and navy is its value. Put semicolons between declarations and braces around the declaration block. A class can be reused on several elements.
Sometimes several declarations compete. Within the ordinary author rules we use here, a class selector is more specific than a type selector: .intro beats p. When competing selectors have equal specificity, the later declaration wins. These are useful starting rules, not the entire cascade: importance, origins and layers also participate. We will avoid inline styles, ids as selectors and !important in this pilot.
Some properties, including color and font-family, inherit from an element's parent when the element has no direct value. A direct rule for a paragraph takes precedence over an inherited body colour. Margins and padding do not generally inherit. Set common text choices on body, then use a class for a deliberate exception.
If a colour is unexpected, inspect the element in browser developer tools. The Styles panel shows matching rules and crossed-out declarations. Start with the rule actually affecting the element. Adding more and more stronger selectors makes future changes harder to understand.
Working example
The HTML shown here is the body fragment. The download includes the complete document.
<main><h1>A learning journal</h1><p class="intro">A short introduction.</p><p>A normal paragraph.</p></main>styles.css
body { font-family: Arial, sans-serif; color: #182826; }
p { color: #394c47; }
.intro { color: #075b43; }
p { color: #4a315d; }Try a change
Predict the colour of each paragraph, then open the example. Add a second .intro rule at the end with color: #173d70. Explain which rule now controls the introduction.
What you should observe
The ordinary paragraph uses the later p colour. The introduction follows the class rule despite the later p rule. The second .intro rule then wins over the first because their specificity is equal.
Check your understanding
If body has a colour but a paragraph has its own matching colour rule, which does the paragraph use?
Read the explanation
The direct paragraph declaration. Inheritance supplies a value when the paragraph does not already have its own cascaded colour.