Skip to content

Selectors

How to link CSS to specific pieces of HTML

  • Lesson
  • 2 min read
  • 1 of 8 in this chapter

When you write inline CSS, it's clear which element you are styling. But internal and external CSS needs selectors to specify which styles go with which HTML elements.

Name

Name selectors state the type of element you want to target, and would apply to all elements with that name. For example, type this in your CSS file:

CSS
h1 {
    color: red;
}

When you save and view your HTML page in the browser, you'll see that both h1 headings turn red - the styling is applied to all h1 elements.

Class

Another way to select elements is by using the class attribute in HTML. Add a class to the last two paragraphs of the HTML document:

HTML
<p class="apples">This is another paragraph.</p>
<p class="apples">A third paragraph.</p>

Now add the styling for this selector to the CSS file:

CSS
.apples {
    color: blue;
}

The styling is applied to any element with the class "apples".

ID

Finally, you can use the id attribute as a selector. First, add the ID to an HTML element:

HTML
<p id="firstParagraph">This is a paragraph</p>

Then add the CSS, adding a # in front of the ID:

CSS
#firstParagraph {
    color: green;
}

While classes can be used on many different elements, IDs should be unique. Every ID should have only 1 HTML element associated with it.

Divs and spans

Oftentimes, you'll need to group different types of elements for styling purposes (for example, give a heading and the paragraph that goes with it the same font). The div and span tags are useful for this. You can give them class or ID selectors to target them with CSS. Here's an example:

HTML
<div class="profile">
    <h1>John Smith</h1>
    <p>@username123<p>
    <p>Short <span class="yellow">profile bio</span> goes here.<p>
</div>
CSS
.profile {
    color: blue;
}

.yellow {
    color: yellow;
}