CSS Foundations

Lesson 1 of 6

What Is CSS? Selectors and the Cascade

CSS (Cascading Style Sheets) controls how HTML looks: colors, fonts, spacing, layout, and more. HTML says what something is, CSS says how it appears.

Three ways to add CSS

HTML

An external stylesheet, linked from <head>, is almost always the right choice: it's cacheable and keeps style separate from structure.

Selectors

p { color: navy; }              /* every <p> */
.card { padding: 16px; }        /* every element with class="card" */
#logo { width: 120px; }         /* the one element with id="logo" */
nav a { text-decoration: none; } /* every <a> inside a <nav> */
SelectorMatches
elementEvery element of that tag, e.g. p, h1
.classEvery element with that class attribute
#idThe single element with that id
a bEvery b element nested anywhere inside an a

The cascade and specificity

When two rules target the same element and property, CSS decides the winner using specificity: IDs beat classes, classes beat plain elements. If specificity ties, the rule that appears later in the stylesheet wins.

p { color: navy; }        /* specificity: 0-0-1 */
.highlight { color: gold; } /* specificity: 0-1-0, wins over the rule above */
#alert { color: red; }     /* specificity: 1-0-0, wins over both */

WARNING

!important overrides normal specificity entirely and is very hard to override again later. Treat it as a last resort, almost every specificity fight can be solved by writing a more specific (or simpler) selector instead.

📝 Selectors & Cascade Quiz

Passing score: 70%
  1. 1.Given equal specificity, which rule wins when two CSS rules conflict?

  2. 2.An ID selector (#logo) has higher specificity than a class selector (.logo).

  3. 3.A selector that targets every element with class="card" is written as ____card.