Find a course

Module 3: CSS FundamentalsLesson 6 of 1212 min

CSS Syntax, Selectors and the Cascade

Write your first CSS rules, link a stylesheet, target elements with type, class, ID and descendant selectors, and predict which conflicting rule wins.

Step 1 of 14Learn

Anatomy of a CSS rule

In 1996, CSS arrived to solve a growing mess: web pages were full of font and color tags mixed into the HTML, so changing a site's look meant editing every page. CSS moved all of that into separate rules.

A CSS rule looks like this:

h1 {
  color: darkblue;
  font-size: 2.5rem;
}
  • h1 is the selector: which elements the rule applies to.
  • Inside the curly braces are declarations, each a property and a value separated by a colon and ending with a semicolon.

There are three ways to add CSS to a page:

  1. External stylesheet (best): a separate file, such as styles.css, linked in the head with <link rel="stylesheet" href="styles.css">. One file can style every page of a site, and browsers cache it so later pages load faster.
  2. Internal stylesheet: a <style> element in the head. Handy for quick experiments or single pages.
  3. Inline styles: a style attribute on one element, like <p style="color: red">. Avoid these except for special cases: they're hard to maintain and override almost everything else.

A missing semicolon or brace is the most common CSS error. Unlike programming languages, CSS doesn't stop with an error message; the browser just ignores the declaration it can't understand, and sometimes the ones after it, so styles silently fail to appear.

Step 2 of 14Note

Step 3 of 14Practice · Spot the mistake

This CSS should make paragraphs gray and 18 pixels, with 1.6 line height, but some styles are ignored. Tap the line with the error.

Step 4 of 14Diagram

Anatomy of a CSS rule

Anatomy of a CSS ruleParts diagram: p { color: gray; font-size: 18px; }, Selector, Declaration block, Property, Value, Semicolon.p { color: gray;font-size:18px; }SelectorDeclarationblockPropertyValueSemicolon

Tap a shape with to see more.

p { color: gray; font-size: 18px; }
Selector

p: which elements the rule applies to.

Declaration block

Everything between the curly braces.

Property

color: what you want to change.

Value

gray: what you want it to be.

Semicolon

Ends each declaration. A missing one silently breaks the next declaration.

Step 5 of 14Learn

Selectors: choosing what to style

Selectors are how CSS finds elements. The essentials:

SelectorExampleSelects
TypepEvery p element
Class.cardEvery element with class="card"
ID#signupThe one element with id="signup"
Descendantnav aEvery a anywhere inside a nav
Childul > lili elements that are direct children of a ul
Grouph1, h2, h3All three types, sharing one rule
Pseudo-classa:hoverLinks while the pointer is over them

Classes are your main tool. An element can have several classes separated by spaces, class="card featured", and many elements can share a class. That makes classes flexible and reusable: style .button once and use it on every button-like link.

IDs must be unique on a page. They're great for fragment links and form labels, but using them for styling makes CSS harder to override, as you'll see in a moment.

Pseudo-classes style elements in a particular state: :hover, :focus (selected by keyboard or click), :first-child, :nth-child(2). Always style :focus visibly, so keyboard users can see where they are on the page.

Step 6 of 14Note

Step 7 of 14Practice · Match the pairs

Match each selector to what it selects.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. .price
  2. #main-title
  3. footer p
  4. button:hover
  5. h2, h3

Step 8 of 14Learn

The cascade: when rules disagree

What happens when two rules set the same property on the same element?

p { color: black; }
.intro { color: green; }
#welcome { color: purple; }

For <p class="intro" id="welcome">, the text is purple. The browser decides using the cascade, which considers three main things in order:

1. Importance and origin. Your styles beat the browser's defaults. A declaration marked !important beats normal ones, but treat it as a last resort; overusing it creates styles that can't be overridden.

2. Specificity. More specific selectors win. Think of it as a three-part score (IDs, classes, types):

  • p scores (0, 0, 1)
  • .intro scores (0, 1, 0), and pseudo-classes and attribute selectors count as classes too
  • #welcome scores (1, 0, 0)
  • nav .menu a scores (0, 1, 2)

Compare from the left: any ID beats any number of classes, and any class beats any number of type selectors. Inline styles beat all selectors.

3. Order. If specificity ties, the rule that comes last in the CSS wins.

Practical advice: style mostly with classes, keep specificity low and even, and avoid IDs and !important in your stylesheets. Then order is easy to reason about and later rules can override earlier ones predictably.

Step 9 of 14Try the calculator

Specificity scorer

Count the parts of a selector. The score is shown as a single number for easy comparison (IDs × 100 + classes × 10 + types), which works as long as no count reaches 10.

Specificity score
12

Step 10 of 14Practice · Choose one

Which selector wins for a link inside <nav class="menu"> if all set a different color: a, nav a, .menu a or nav .menu a?

Step 11 of 14Note

Step 12 of 14Tap to reveal

Three more selector tools

  1. Attribute selectors

    Select elements by their attributes: input[type="email"] styles only email fields, and a[href^="https"] targets links whose address starts with https. They count as classes for specificity.

  2. Pseudo-elements

    Style a part of an element: p::first-line styles the first line of a paragraph, and ::before and ::after insert decorative content before or after an element. They use two colons and count as type selectors.

  3. :not() and :is()

    Modern helpers: li:not(:last-child) selects every list item except the last, handy for adding dividers between items. :is(h1, h2, h3) a matches links inside any of those headings without repeating the selector.

Step 13 of 14Practice · True or false

If two rules have exactly the same specificity, the one that appears later in the stylesheet wins.

Step 14 of 14Practice · Fill in the blanks

Fill in the blanks

In the selector .card, the dot means it selects by . In #header, the hash means it selects by . A selector with one ID beats a selector with any number of .