Skip to content

Selectors

A selector is how you tell CSS which element to style. So far you have used the element name — like body or h1. But CSS gives you more precise ways to target exactly what you want.


Element selectors

Targets every element of a given tag on the page. Every <p>, every <h2>, every <button>.

p {
  color: #333;
}

h2 {
  color: indigo;
}

One rule, applied to all matching elements automatically.


Class selectors

A class is a label you attach to specific HTML elements. You can apply the same class to as many elements as you like, and they all share the same style.

In your HTML, add a class attribute:

<p class="highlight">This paragraph stands out.</p>
<p>This one is normal.</p>
<p class="highlight">This one stands out too.</p>

In your CSS, target the class with a . before the name:

.highlight {
  background-color: lightyellow;
  color: black;
}

Only the elements with class="highlight" get the style. The middle paragraph stays untouched.


ID selectors

An ID is like a class but unique — only one element per page should have a given ID.

In HTML:

<h1 id="page-title">My Portfolio</h1>

In CSS, target it with a #:

#page-title {
  font-size: 48px;
  color: darkblue;
}

When to use which

Selector Syntax Use when...
Element h1 { } Styling all elements of that type
Class .name { } Styling specific elements, reusable
ID #name { } Styling one unique element

Classes are the most useful — you will use them constantly. IDs are for genuinely unique things. Element selectors set broad defaults.


Challenge

In portfolio.html:

  • Add class="section-heading" to two of your <h2> tags
  • In style.css, write a rule for .section-heading that gives it a different colour and adds border-bottom: 2px solid indigo;
  • Add id="intro" to one of your paragraphs and give it a slightly different background colour

Refresh. Notice that only the elements you targeted changed — everything else stays the same.


← What is CSS?    Next: Colors and Backgrounds →