Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

Applying Styles: Tag, Class & ID

5 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 3 deck

Applying Styles: Tag, Class & ID
Fullscreen for presentation · Print / PDF for a handout
1 / 5
Lesson

Applying Styles: Tag, Class & ID

The three core ways to target elements, and when to use each.

Applying Styles: Tag, Class & ID

Ways to Apply CSS Rules

MethodSyntaxNotes
Tag selectorh1 { color: blue; }Affects every <h1> on the page. Good for global defaults.
Class attribute.highlight { color: red; }Reusable across many elements. Best for repeated styles.
ID attribute#hero { font-size: 3rem; }Unique — one element per page. Highest CSS specificity.
Applying Styles: Tag, Class & ID

The Class Attribute

Classes let different occurrences of the same tag use different styles.

/* Attached class */
p.narrow { width: 380px; }
p.wide   { width: 680px; }

/* Generic class — applies to any tag */
.highlight { background-color: yellow; font-weight: bold; }

/* Multiple classes on one element */
.card { border-radius: 8px; }
.card.featured { border: 2px solid gold; }

Applied in HTML with the class attribute:

<p class="narrow">...</p>
<div class="card featured large">...</div>

2025 best practice: use BEM naming — .card, .card__title, .card--featured.

Applying Styles: Tag, Class & ID

The ID Attribute

An ID is unique — each value can be used only once per HTML document.

<p id="header">...</p>
#header { font-size: 2rem; }
  • Higher specificity than class selectors.
  • Use IDs for landmark regions: #main-nav, #hero, #footer.
  • Avoid using IDs just for styling — prefer classes for reusability.
  • IDs are also used as anchor links: <a href="#section2">.
Applying Styles: Tag, Class & ID

Activity — complete the code

Complete the tag, class and ID selectors.

/* Tag selector */
p { color: black; }
 
/* Class selector */
{ color: red; }
 
/* ID selector */
{ font-size: 3rem; }