On this page
Introduction to CSS
What is CSS?
CSS (Cascading Style Sheets) is the language used to style HTML documents. It controls colors, fonts, spacing, layout, and much more.
Without CSS, web pages would look like plain, unformatted text documents.
How to add CSS
There are three ways to add CSS to an HTML document:
- Inline --
styleattribute on the element (not recommended) - Internal --
<style>tag in the<head> - External --
.cssfile linked with<link>(recommended)
The recommended approach is to use external files because it separates presentation from structure.
The cascade
The "C" in CSS stands for "Cascading." When there are conflicts between styles, the browser follows rules to decide which one to apply:
- Origin -- Author styles vs browser styles
- Specificity -- How specific the selector is
- Order -- The last declared style wins
Specificity
Specificity determines which styles take priority. From lowest to highest:
- Type selectors (
h1,p) -- Low specificity - Class selectors (
.card) -- Medium specificity - ID selectors (
#hero) -- High specificity - Inline styles -- Maximum specificity
In the next lesson, we will dive deeper into CSS selector types.
Practice
- Create an external stylesheet: Create a
styles.cssfile and link it to an HTML document with<link>. Define styles forh1, a.highlightedclass, and a#mainID. - Experiment with the cascade: Write two rules that target the same paragraph (one with a type selector and another with a class selector) and verify which one wins based on specificity.
- Compare the three methods: Apply the same background color to a
<div>using inline, internal, and external styles. Observe which takes priority and why.
Best practice
Prefer class selectors over ID selectors. Classes are reusable and have lower specificity, making maintenance easier.
/* Type selector */
h1 {
color: #1a1a2e;
font-size: 2rem;
}
/* Class selector */
.highlighted {
background-color: #ffd700;
padding: 0.5rem 1rem;
border-radius: 4px;
}
/* ID selector */
#hero {
text-align: center;
margin-top: 2rem;
}
Sign in to track your progress