Log inSign up free
Mastering Modern CSS: From Zero to Pro
  1. Getting started

    1. CSS Lesson 1: What Is CSS?
    2. CSS Lesson 2: Selectors and Rules
    3. CSS Lesson 3: How CSS Works: The Cascade
    4. CSS Lesson 4: Colour and Backgrounds
    5. CSS Lesson 5: Typography and Text
    6. CSS Lesson 6: The Box Model
    7. CSS Lesson 7: Units and Sizing
    8. CSS Lesson 8: Display and Positioning
    9. CSS Lesson 9: Flexbox
    10. CSS Lesson 10: Grid
    11. CSS Lesson 11: Responsive Design
    12. CSS Lesson 12: Final Project
Mastering Modern CSS: From Zero to Pro

Getting started · Lesson 2 of 12 · 10 min read · By Jack

CSS Lesson 2: Selectors and Rules

Learn how to target exactly the HTML elements you want to style, using element, class and ID selectors, and how to group and combine them.

Downloads for this lesson

Sign up free (or log in) to download these files.

Estimated time: 15 minutes reading, plus about 25 minutes of practice.

Downloads (at the top of this lesson):

  • css_lesson2_selector_cheat_sheet.pdf is a printable guide to every selector in this lesson, with a class vs ID table, a specificity preview and a debugging checklist.
  • css_lesson2_selector_reference.csv lists 14 selectors with type, example and what each matches.
  • css_lesson2_practice_tracker.csv is a checklist of this lesson's tasks.

Answers are hidden. Chat can't fold answers away, so all of them sit in the Answer Key at the very end. Try each question first, then scroll down to check.

Learning goals: By the end, you'll be able to:

  • target elements with element, class and ID selectors
  • group selectors and combine them
  • use descendant and child selectors
  • style links and inputs with :hover and :focus
  • choose good class names and debug a selector that isn't working

Part 1: What does a selector do? (2 min)

A selector is the "address" of the elements you want to style. Lesson 1 used p and h1. Now you'll learn to be far more precise.

selector {  
  property: value;  
}

Use this HTML for the examples in this lesson:

<body>  
  <header>  
    <h1 id="site-title">Garden Club</h1>  
    <nav>  
      <a href="#events">Events</a>  
      <a href="#join">Join</a>  
    </nav>  
  </header>  
  
  <main>  
    <h2>Welcome</h2>  
    <p class="note">New members are always welcome.</p>  
    <p>We meet every Saturday.</p>  
  
    <ul>  
      <li>Planting</li>  
      <li class="featured">Seed swap</li>  
      <li>Tea</li>  
    </ul>  
  </main>  
</body>

Quick check A. Without scrolling, which element does the selector h2 match in the HTML above?


Part 2: Element selectors and grouping (2 min)

An element selector (also called a type selector) matches every element of that name.

p {  
  color: #374151;  
}

This styles both paragraphs. Use element selectors for broad, site-wide defaults.

Grouping. When several elements share styles, separate selectors with commas.

h1, h2, h3 {  
  font-family: Georgia, serif;  
  color: #14532d;  
}

This is shorter and easier to maintain than three separate rules.

The universal selector * matches everything. It's often used for a quick reset:

* {  
  margin: 0;  
  box-sizing: border-box;  
}

(We'll explain these properties in Lesson 7.)

Quick check B. Write one rule that makes all <h2> and <li> elements dark green (darkgreen).


Part 3: Class selectors (3 min)

An element selector styles all paragraphs. What if you want to style only some? Add a class in the HTML, then target it in CSS with a dot.

<p class="note">New members are always welcome.</p>  
<p>We meet every Saturday.</p>
.note {  
  background-color: #fef9c3;  
  border-left: 4px solid #eab308;  
  padding: 8px;  
}

Only the first paragraph is styled.

Key facts about classes:

  • A class can be used on as many elements as you like.
  • An element can have several classes, separated by spaces.
  • In HTML you write class="note", with no dot. In CSS you write .note, with a dot.
<p class="note important">Bring gloves.</p>
.note { background-color: #fef9c3; }  
.important { font-weight: bold; }

The paragraph gets both styles.

Combining element and class. p.note matches only <p> elements with that class, with no space and no dot after p.

p.note { font-style: italic; }  
li.featured { color: crimson; }

Requiring two classes. .note.important (no space) matches only elements that have both classes.

Quick check C. What is the difference between .note and p.note?

Quick check D. What's wrong with this pair?

<p class=".note">Hello</p>
note { color: red; }

Part 4: ID selectors (2 min)

An ID identifies one unique element on the page. In CSS, use a hash.

<h1 id="site-title">Garden Club</h1>
#site-title {  
  text-align: center;  
}
ClassID
CSS symbol.#
Uses per pageUnlimitedOnce only
Several on one element?YesNo
Best forStylingJump links and unique hooks

Best practice: style with classes, and keep IDs for in-page links (Lesson 4: href="#join") and special cases. IDs are very strong in the cascade, which makes them hard to override later (Lesson 3).

Quick check E. Can two elements on a page share id="intro"? Can two elements share class="intro"?


Part 5: Combining selectors (3 min)

You can target elements based on where they sit in the HTML.

Descendant selector (a space)

Matches an element anywhere inside another.

nav a {  
  color: darkgreen;  
  text-decoration: none;  
}

This styles every <a> inside a <nav>, however deep. Links elsewhere are unaffected.

Child selector (>)

Matches only direct children.

ul > li {  
  margin-bottom: 6px;  
}

If you nest a second <ul> inside an <li>, ul > li still matches the inner items, because each is a direct child of its own <ul>. A ul > li > a chain, however, only matches links sitting directly inside those <li> elements, not links deeper inside other elements.

Descendant vs. child:

<div>  
  <p>Direct child of div</p>  
  <section>  
    <p>Descendant of div, but not a child</p>  
  </section>  
</div>
SelectorMatches
div pBoth paragraphs
div > pOnly the first

Adjacent sibling selector (+)

Matches an element immediately after another at the same level.

h2 + p {  
  font-size: 1.2em;  
}

This styles the first paragraph right after each <h2>, which is handy for a lead-in paragraph.

Quick check F. In the Garden Club HTML, which selector would style only the links inside <nav>: nav a or header a? Why might the second be a poor choice if you later add a link to the header?

Quick check G. What does div > p match that div p doesn't? And the other way round?


Part 6: Attribute and pseudo-class selectors (2 min)

These are previews. You'll use them a lot later.

Attribute selectors match by an HTML attribute.

a[target="_blank"] {  
  color: purple;  
}  
  
input[type="email"] {  
  border: 2px solid #3b82f6;  
}

Pseudo-classes match an element in a particular state. They start with a colon.

a:hover {  
  color: tomato;  
}  
  
input:focus {  
  background-color: #eff6ff;  
  outline: 2px solid #3b82f6;  
}  
  
li:first-child {  
  font-weight: bold;  
}
Pseudo-classWhen it applies
:hoverMouse is over the element
:focusElement is selected (for example, a form field being typed in)
:first-childThe element is the first child of its parent

Lesson 3 will cover specificity, and pseudo-classes get their own lesson later.


Part 7: Naming and organising (1 min)

Good class names make CSS easy to read.

AvoidPreferWhy
.red-text.warningIf the colour changes, the name is wrong
.Box1.event-cardDescribe the purpose
.my class.my-classNo spaces
.1stItem.first-itemCan't start with a digit

Conventions:

  • lowercase, with hyphens between words (.main-menu)
  • one clear purpose per class
  • put related rules together and label sections with comments:
/* ===== Navigation ===== */  
nav a { ... }  
nav a:hover { ... }

Specificity preview. When two rules conflict, the more specific selector wins, in this order: inline style, then ID, then class, attribute or pseudo-class, then element. If they tie, the later rule wins.

p { color: black; }  
.note { color: green; }

A <p class="note"> is green, because the class is more specific than the element.


Common mistakes

MistakeFix
.note in HTML: class=".note"Leave out the dot in HTML
note { } for a classAdd the dot: .note { }
p .note when you meant p.noteThe space means "inside a p"
Using one ID on many elementsUse a class instead
Typos like class="Note" vs .noteNames are case-sensitive in practice, so keep them lowercase
Overusing IDs for stylingUse classes
Long chains like body div ul li aKeep selectors short

Debugging a selector that does nothing

  1. Check the dot or hash.
  2. Check the spelling against the HTML.
  3. Right-click, Inspect, and see whether your rule appears in the Styles panel.
  4. A struck-through rule means something stronger overrode it.

Key takeaways

  • Element selectors style every matching element, classes (.) style chosen groups, and IDs (#) style one unique element.
  • Group selectors with commas to share styles.
  • A space means descendant, > means direct child, and + means adjacent sibling.
  • Pseudo-classes like :hover and :focus style states.
  • Prefer classes for styling, and name them by purpose.
  • If rules conflict, specificity decides, then the later rule wins.

Exercises (25 min)

1. Identify (3 min). Name the type of selector in each:

  • a) p
  • b) .card
  • c) #footer
  • d) nav a
  • e) ul > li
  • f) h1, h2

2. Write the selector (4 min). Using the Garden Club HTML, write the selector for:

  • a) the <h1> using its ID
  • b) only the <li> with the class featured
  • c) all links inside <nav>
  • d) the paragraph straight after the <h2>

3. Fix the errors (5 min).

.note  
  color: blue;  
}  
  
#intro, #intro {  
  color = red;  
}  
  
h1 h2 {  
  color: green;  
}  
  
Note {  
  font-weight: bold  
}

Imagine you wanted: a blue .note class, a red #intro heading, and green h1 and h2 headings together.

4. Predict the result (3 min).

<p class="note" id="lead">Hello</p>
p { color: black; }  
.note { color: green; }  
#lead { color: blue; }

What colour is the text, and why?

5. Build it: recipe page mini project (8 min). Create recipe.html and recipe.css:

  1. Add a <header> with an <h1 id="page-title">, and a <nav> with three links.
  2. Add a <main> with an <h2>, an intro <p class="intro">, an ordered list of steps and a second <p class="tip">.
  3. In the CSS, write:
    • a grouped rule for h1, h2
    • a .tip class with a background colour and border
    • an #page-title rule that centres it
    • nav a and nav a:hover
    • ol > li with some bottom margin
    • an h2 + p rule for the lead paragraph
  4. Add a comment heading for each section of your CSS.

6. Challenge (2 min). Add a[target="_blank"] styling and input:focus styling to a page with an external link and a form field. Check both in your browser.


Lesson 2 checkpoint

  • I can use element, class and ID selectors.
  • I can group selectors with commas.
  • I know the difference between p.note, p .note and .note.important.
  • I can write descendant and child selectors.
  • I can style :hover and :focus.
  • I can name classes by purpose and debug a missing style.


⬇️ ANSWER KEY (only scroll once you've tried the questions)

Quick check A: the <h2>Welcome</h2>, the only <h2> on the page.

Quick check B:

h2, li {  
  color: darkgreen;  
}

Quick check C: .note matches any element with the class note. p.note matches only <p> elements with that class, so a <div class="note"> would be left out.

Quick check D: In HTML, the class shouldn't have a dot: class="note". In CSS, the selector needs a dot: .note { color: red; }.

Quick check E: No, an ID must be unique on a page. Yes, classes can be shared by any number of elements.

Quick check F: nav a. header a would also match any link you later add to the header outside the nav, causing unwanted styling.

Quick check G: div > p doesn't match paragraphs nested deeper (such as inside a <section>), but div p does. Everything div > p matches is also matched by div p, so nothing is matched by div > p alone.

Exercise 1:

  • a) element (type) selector
  • b) class selector
  • c) ID selector
  • d) descendant selector
  • e) child selector
  • f) grouping (selector list)

Exercise 2:

  • a) #site-title
  • b) li.featured (or .featured)
  • c) nav a
  • d) h2 + p

Exercise 3 (corrected):

.note {  
  color: blue;  
}  
  
#intro {  
  color: red;  
}  
  
h1, h2 {  
  color: green;  
}  
  
.note {  
  font-weight: bold;  
}

Errors fixed: missing { after .note, = replaced with :, the duplicate #intro removed, h1 h2 (descendant: an h2 inside an h1) changed to h1, h2 (grouping), and Note changed to .note with a semicolon added. The last .note rule could also be merged into the first.

Exercise 4: Blue. All three rules match, and the ID selector #lead is more specific than the class, which is more specific than the element.

Exercise 5: Check your work against the tracker and the checklist: every rule type from the brief should appear at least once, each section should have a comment, and hovering a nav link should change its appearance.

Exercise 6 (example):

a[target="_blank"] {  
  color: purple;  
}  
  
input:focus {  
  outline: 2px solid #3b82f6;  
  background-color: #eff6ff;  
}

Keep track of your learning

This lesson comes with 3 downloads. Create a free account to unlock them and track your progress.

  • Track your progress through every course
  • Take the quizzes and see your score
  • Download the worksheets and resources
  • Get a certificate when you finish

Related reading on our blog

Rather have it done for you?

We build websites for small businesses

Everything in this course is what we do every day for local businesses: fast, mobile-friendly sites that are built to be found on Google. See our web design services or our website packages.