CSSLesson 2 of 10Jump to practice

CSS selectors

Target elements by name, by class or by id, and learn when to use each one.

The selector is the part of a rule that decides which elements it styles. Here are the three you will use most.

Selector Example Selects
Element p Every <p>
Class .warning Every element with class="warning"
ID #signup The one element with id="signup"

Classes

A class lets you style some elements of a type but not others. Add a class attribute in HTML, then select it in CSS with a dot.

Styling with a class
Open in editor
<!DOCTYPE html>
<html>
<head>
<style>
  p { color: #333; }

  .warning {
    color: #9a3412;
    background: #ffedd5;
    padding: 8px 12px;
  }
</style>
</head>
<body>
<p>A normal paragraph.</p>
<p class="warning">This paragraph has the warning class.</p>
<p>Another normal paragraph.</p>
</body>
</html>
Result

An element can have more than one class. Separate them with spaces: class="warning big".

IDs

An id must be unique on the page. Select it with #.

#signup {
  border: 2px solid teal;
}

Grouping

To give several selectors the same style, separate them with commas:

Grouped selectors
Open in editor
<!DOCTYPE html>
<html>
<head>
<style>
  h1, h2, h3 {
    font-family: sans-serif;
    color: navy;
  }
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
</body>
</html>
Result

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Select every element with the class price.

     {
      font-weight: bold;
    }

  2. Exercise 2

    Select the one element with the id menu.

     {
      background: navy;
    }

  3. Exercise 3

    Give the paragraph the class note in the HTML.

    <p ="note">Remember to save your work.</p>

Quiz: 4 questions

1. Which selector matches <p class="intro">?
2. How many elements on a page should share one id?
3. What does h1, h2 { color: navy; } do?
4. How do you give an element two classes?

Finish the practice to complete this lesson.