Episode 8 of 53

Targeting Elements in CSS

Learn how to use element selectors (type selectors) to target and style HTML elements.

The most basic way to apply styles in CSS is with element selectors (also called type selectors). You simply use the name of the HTML element.

Element Selectors

/* Target all paragraphs */
p {
    color: #333;
    line-height: 1.6;
}

/* Target all h1 headings */
h1 {
    font-size: 2.5rem;
    color: navy;
}

/* Target all links */
a {
    color: teal;
    text-decoration: none;
}

How It Works

When you write p { ... }, the styles apply to every single <p> element on the page. This is powerful for setting base styles but can be too broad if you want different paragraphs to look different.

Classes and IDs

For more targeted styling, you can use classes and IDs:

/* Class selector — reusable */
.highlight {
    background-color: yellow;
    padding: 0.25rem;
}

/* ID selector — unique per page */
#main-title {
    font-size: 3rem;
    text-align: center;
}

In HTML:

<h1 id="main-title">Welcome</h1>
<p class="highlight">This is highlighted.</p>
<p>This is not highlighted.</p>
  • Classes use a dot . prefix
  • IDs use a hash # prefix
  • Classes can be reused; IDs should be unique per page