Lesson 7 of 14 · 8 min

Classes and ids

Styling p changes every paragraph. Usually you want to style only some elements. That is what classes and ids are for.

class

Add a class attribute in HTML, then select it in CSS with a dot:

<p class="warning">Mind the step.</p>
.warning {
  color: crimson;
}

Many elements can share a class, and one element can have several classes, separated by spaces: class="warning big".

id

An id names one unique element on the page. Select it with a hash:

<h1 id="title">Welcome</h1>
#title {
  color: navy;
}

Use classes for styling (they are reusable) and ids for the few elements that are truly unique, like the main title or a section people can link to (page.html#contact).

Your task

  1. Give the second paragraph the class highlight, and make .highlight have a yellow background.
  2. Give the heading the id title, and make #title navy.

Write the CSS in style.css.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Classes and ids</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Market day</h1>
  <p>The market opens at seven.</p>
  <p>Fresh tomatoes are half price today!</p>
  <p>Bring your own bags.</p>
</body>
</html>

Your page

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…