On this page

Introduction to CSS

10 min read TextCh. 1 — CSS Basics

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:

  1. Inline -- style attribute on the element (not recommended)
  2. Internal -- <style> tag in the <head>
  3. External -- .css file 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:

  1. Origin -- Author styles vs browser styles
  2. Specificity -- How specific the selector is
  3. 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

  1. Create an external stylesheet: Create a styles.css file and link it to an HTML document with <link>. Define styles for h1, a .highlighted class, and a #main ID.
  2. 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.
  3. 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;
}