Webbo3 Frontend Development · Month 1 · Lesson 9
Introduction to CSS and the Cascade
Learn about CSS selectors cascade specificity to predict which rule wins when styles conflict and apply CSS in different ways.
You've been writing HTML for a while now, and you're probably tired of how plain and unstyled your web pages look. You might have even tried to add some color or change the font, but you're not sure how to do it or where to put the code. Maybe you've heard of CSS, but you're not sure what it does or how it works. By the end of this lesson, you'll be able to make your web pages look more visually appealing by applying CSS styles to your HTML elements. You'll be able to change the color, font, and layout of your pages, and you'll understand how to apply these styles in different ways. As you start working with CSS, you'll notice that sometimes multiple styles seem to be fighting with each other. You might set the background color of a paragraph to blue, but then you set it to red somewhere else, and you're not sure which one will win. This is where the concept of the cascade comes in, which is a fundamental idea in CSS. The cascade is what determines which style rule takes precedence when there are multiple rules that apply to the same element. By the end of this lesson, you'll be able to predict which rule will win when two or more rules conflict, and you'll be able to use this knowledge to create web pages that look exactly how you want them to. By the end of this lesson, you'll be able to apply CSS styles to your HTML elements in three different ways: inline, internal, and external. You'll understand the pros and cons of each method, and you'll be able to choose the best approach for your project. You'll also be able to resolve conflicts between multiple style rules, and you'll be able to use the cascade to your advantage to create complex and visually appealing web pages. With this knowledge, you'll be able to take your web development skills to the next level and create professional-looking web pages that engage and impress your users.
What you need before starting
Everything from the previous lesson, and the project folder you have been building in. Work along in your own editor as you read — this lesson is written to be typed, not skimmed.
The Three Ways to Apply CSS
Inline, Internal, and External Styles
There are three ways to apply CSS to an HTML document: inline, internal, and external styles. Inline styles are applied directly to an HTML element using the style attribute. Internal styles are defined in the HTML document's head section using the style element. External styles are defined in a separate CSS file and linked to the HTML document. For example, let's consider a simple HTML document with a paragraph element:
<p>This text is red.</p>In this example, the color of the text is set to red using an inline style. Internal styles can be defined in the head section of the HTML document:
<head>
<style>
p {
color: blue;
}
</style>
</head>
<body>
<p>This text is blue.</p>
</body>In this example, all paragraph elements in the document will have blue text. External styles are the most commonly used method in real projects. They are defined in a separate CSS file and linked to the HTML document:
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<p>This text will be styled by the external stylesheet.</p>
</body>The CSS file, style.css, would contain the styles:
p {
color: green;
}External styles win in real projects because they allow for better organization and reusability of code. A single CSS file can be linked to multiple HTML documents, making it easier to maintain a consistent look and feel across a website.
Grouping and Combining Selectors
Selector Syntax and Precedence
CSS selectors can be grouped and combined to target multiple elements with a single style rule. For example, to set the color of all paragraph and heading elements to black:
p, h1, h2 {
color: black;
}This will apply the style to all paragraph, h1, and h2 elements in the document. Selectors can also be combined using descendant, child, and adjacent sibling combinators. For example, to set the color of all paragraph elements that are descendants of a div element:
div p {
color: gray;
}A common mistake beginners make is using the wrong combinator or misunderstanding the precedence of selectors. For example, the selector `div p` will target all paragraph elements that are descendants of a div element, not just direct children. To target only direct children, the `>` combinator should be used: `div > p`.
Specificity and Precedence
CSS styles are applied based on specificity and precedence. Inline styles have the highest specificity, followed by ID selectors, class selectors, and tag selectors. When multiple styles are applied to an element, the style with the highest specificity wins. For example:
<p id="para">This text will be styled by the ID selector.</p>
<style>
#para {
color: red;
}
.text {
color: blue;
}
</style>In this example, the color of the text will be red, because the ID selector `#para` has higher specificity than the class selector `.text`.
The !important Keyword
A Sign of Something Gone Wrong
The `!important` keyword is used to override the normal specificity and precedence rules in CSS. It should be used sparingly, as it can make debugging and maintaining styles more difficult. For example:
<p>This text will be styled by the !important declaration.</p>
<style>
.text {
color: blue;
}
.text {
color: red !important;
}
</style>In this example, the color of the text will be red, because the `!important` declaration overrides the previous style. A common mistake beginners make is overusing the `!important` keyword to fix styling issues, rather than taking the time to understand the underlying specificity and precedence rules. This can lead to a stylesheet that is difficult to maintain and debug. Instead, beginners should take the time to understand how CSS styles are applied and use the `!important` keyword only when necessary.

Anatomy of a Rule
Breaking Down a CSS Rule
A CSS rule is made up of a selector, property, value, and declaration block. The selector is used to target the HTML element you want to style. The property is the aspect of the element you want to change, such as color or font size. The value is the specific change you want to make to the property. The declaration block is where you group multiple properties and values for a single selector. For example, consider the following CSS rule:
h1 {
color: #00698f;
font-size: 36px;
}In this rule, `h1` is the selector, `color` and `font-size` are properties, and `#00698f` and `36px` are values. The curly brackets `{}` form the declaration block.
Understanding Selectors, Properties, and Values
It's essential to understand how to write selectors, properties, and values correctly. A common mistake beginners make is using the wrong syntax for selectors, such as using a period (.) instead of a hash (#) for ID selectors. For example, if you have an HTML element with the ID "header", the correct CSS selector would be `#header`, not `.header`. To spot this mistake, make sure to check your selector syntax and ensure you're using the correct symbol for the type of selector you're using.
What the Cascade Actually Is
Understanding the Cascade
The cascade in CSS refers to the way styles are applied to elements based on their proximity to the element, the importance of the style, and the order in which the styles are defined. When multiple styles are applied to the same element, the cascade determines which style takes precedence. The cascade is based on three factors: importance, specificity, and order.
Importance, Specificity, and Order
Importance refers to the use of the `!important` keyword, which overrides all other styles. Specificity refers to how specific a selector is, with more specific selectors taking precedence over less specific ones. Order refers to the order in which styles are defined, with later styles overriding earlier ones. Understanding the cascade is crucial to writing effective CSS code and avoiding conflicts between styles.
Linking a Stylesheet Correctly
Using the Link Tag
To link a stylesheet to an HTML document, you use the `link` tag in the `head` section of the HTML file. The `link` tag has several attributes, including `rel`, `href`, and `type`. The `rel` attribute specifies the relationship between the HTML file and the stylesheet, the `href` attribute specifies the location of the stylesheet, and the `type` attribute specifies the type of the stylesheet.
Example of Linking a Stylesheet
Here's an example of how to link a stylesheet to an HTML file:
<head>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>In this example, the `link` tag is used to link a stylesheet named "styles.css" to the HTML file. The `rel` attribute is set to "stylesheet", the `href` attribute is set to "styles.css", and the `type` attribute is set to "text/css". A common mistake beginners make is forgetting to specify the `type` attribute or specifying it incorrectly. To spot this mistake, make sure to check the `type` attribute and ensure it's set to "text/css" for CSS stylesheets. Also, ensure the `href` attribute points to the correct location of the stylesheet file.
Element, Class and ID Selectors
Understanding the Basics
When working with CSS, you need to target specific parts of your HTML document to apply styles. This is achieved using selectors. There are three main types of selectors: element, class, and ID selectors. Element selectors target HTML elements directly, such as paragraphs or headings. Class selectors target elements based on the class attribute, allowing you to style multiple elements at once. ID selectors target elements based on their unique ID.
For example, if you have a paragraph element in your HTML, you can target it using an element selector like this: p { color: blue; }. This will apply the style to all paragraph elements in your document.
Class and ID Selectors
To use class or ID selectors, you first need to add a class or ID attribute to the element in your HTML. For instance, <p>Introduction</p> or <p id="main-paragraph">Main paragraph</p>. Then, in your CSS, you can target these elements using a dot (.) for classes and a hash (#) for IDs: .intro { color: red; } or #main-paragraph { font-size: 20px; }.

Specificity Explained
A Simple Counting System
Specificity is a system used by browsers to determine which CSS rule applies when there are multiple rules that could apply to the same element. It's based on a simple counting system. Each type of selector has a different weight: element selectors count as 1, class selectors count as 10, and ID selectors count as 100. When multiple rules apply to the same element, the browser adds up the weights of the selectors in each rule and applies the rule with the highest total weight.
Worked Examples
Consider the following example:
p { color: blue; } /* Element selector, weight = 1 */
.intro { color: red; } /* Class selector, weight = 10 */
#main-paragraph { color: green; } /* ID selector, weight = 100 */
<p id="main-paragraph">Hello, world!</p>In this case, despite having multiple rules that could apply to the paragraph element, the rule with the highest weight is the ID selector (#main-paragraph), so the text color will be green.
A common mistake beginners make is not considering the weights of selectors when writing their CSS rules, leading to unexpected styling. To spot this, look for places where multiple rules could apply to the same element and calculate the weights of the selectors involved.
Let's consider another example where we have multiple class selectors and an element selector:
p { color: blue; } /* Element selector, weight = 1 */
.special-text { color: red; } /* Class selector, weight = 10 */
.important { font-weight: bold; } /* Class selector, weight = 10 */
<p>Important text</p>In this scenario, both class selectors apply to the paragraph element. However, since both have the same weight (10), and there's also an element selector with a lower weight (1), the styles from all applicable rules are applied where possible. The text will be red and bold, because both class selectors are applied, and the element selector's style (color: blue) is overridden by one of the class selectors (.special-text { color: red; }).
Do this now
To understand how the CSS cascade works, you will write four conflicting rules for the same element, predict which one wins, and then check in the browser. This exercise should take about 20 minutes to complete. Follow these steps:
- Create a new file called `cascade.html` and add a simple HTML structure with one paragraph element, like this:
HTMLExample and result
<p>Hello, world!</p>Result - Create a new file called `cascade.css` and add four conflicting rules for the paragraph element, such as different colors, fonts, and font sizes.
- Predict on paper which rule you think will win and why, based on what you've learned about the CSS cascade.
- Link the `cascade.css` file to the `cascade.html` file and open `cascade.html` in your browser to see which rule actually wins.
Be careful not to make the common mistake of assuming that the last rule always wins. The cascade is more complex than that.
How to know you got it right
To verify that you have completed the exercise correctly, check the following:
- You have four conflicting rules in your `cascade.css` file.
- You made a prediction about which rule would win before checking in the browser.
- You linked the `cascade.css` file to the `cascade.html` file and checked the result in the browser.
- You can explain why the winning rule was chosen by the browser, based on the CSS cascade rules.
If you can verify all of these points, you have successfully completed the exercise and should have a better understanding of the CSS cascade.
Common mistakes
- Not understanding the cascade: It looks like a beginner writing multiple styles for the same element, wondering why only one works. This happens because they don't grasp how CSS rules interact. The fix is to learn about specificity and how the cascade resolves conflicts.
- Confusing CSS and HTML: This error looks like a beginner trying to use CSS syntax in HTML files or vice versa. It happens due to a lack of understanding of the roles of each language. The fix is to clearly separate CSS and HTML code into their respective files.
- Not using the browser's developer tools: It looks like a beginner struggling to find the source of a styling issue. This happens because they're not using the developer tools to inspect elements and see applied styles. The fix is to learn how to use the developer tools for debugging.
- Writing overly specific selectors: This mistake looks like a beginner writing selectors that are too long or complex. It happens because they're trying to target a specific element without understanding how selectors work. The fix is to learn about selector specificity and how to write efficient, reusable selectors.
Questions students ask
- What is the purpose of the cascade in CSS? The cascade helps resolve conflicts between multiple styles applied to the same element, ensuring that the most specific rule is applied.
- How do I know which CSS rule is being applied to an element? Use the browser's developer tools to inspect the element and see which styles are being applied, and from which CSS rule.
- Can I write CSS code directly in my HTML file? While it's possible to write CSS code directly in an HTML file, it's generally better to keep CSS code in a separate file to maintain organization and reusability.
Quick recap: The Three Ways to Apply CSS · Grouping and Combining Selectors · The !important Keyword · Anatomy of a Rule · What the Cascade Actually Is · Linking a Stylesheet Correctly · Element, Class and ID Selectors · Specificity Explained
Next lesson: Colour, Typography and the Box Model.