Kodokon kodokon.com

Basic selectors and colors

Learn to target elements precisely with element, class and id selectors, then apply colors to them.

9 min · 3 questions

Open this lesson in Kodokon

A selector is the part of a CSS rule that says which elements to style. The simplest one is the element selector: you write the tag name, without angle brackets. p targets every paragraph, h1 every top-level heading. That works well, but it is sometimes too broad: what if you wanted to color just one paragraph out of ten? That is where classes and ids come in.

A class is a label you attach to one or more HTML elements with the class attribute. On the CSS side, you target it with a dot: .important selects every element carrying class="important". An id is a unique label: it must appear only once per page, for example on the header. On the CSS side, you target it with a hash: #header.

HTML
<h1 id="main-title">My cooking blog</h1>
<p class="highlight">Recipe of the day: the pie.</p>
<p>A perfectly ordinary paragraph.</p>
<p class="highlight">Tip: preheat the oven.</p>
A unique id on the heading, one class reused on two <p> tags.
CSS
#main-title {
  color: darkgreen;
}

.highlight {
  background-color: yellow;
}

p {
  color: black;
}
The hash # targets an id, the dot . targets a class.

In this example, the heading turns dark green, the two paragraphs labeled highlight get a yellow background (background-color sets the background color), and every paragraph has black text. Remember the difference: a class is reusable on as many elements as you like, while an id is unique within the page. When in doubt, use a class.

Now let's talk about colors. CSS accepts several notations. Color names (red, blue, orange...) are simple but limited. The hexadecimal notation starts with # followed by six characters that dose the red, the green and the blue: #ff0000 is a pure red. Finally, the rgb() notation expresses the same doses with numbers from 0 to 255: rgb(255, 0, 0) is also a pure red.

CSS
.highlight {
  color: tomato;
  background-color: #fff3cd;
}

#main-title {
  color: rgb(0, 100, 0);
}
Three ways to write a color: name, hexadecimal and rgb().

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which CSS selector targets every element carrying class="menu"?
    • #menu
    • .menu
    • menu
    • class.menu
  2. What is the main difference between a class and an id?
    • An id can be placed on several elements, a class cannot
    • A class is reusable, an id must be unique within the page
    • Classes only work on paragraphs
  3. Which of these values represents a pure red?
    • rgb(0, 0, 255)
    • #00ff00
    • #ff0000
    • rgb(0, 255, 0)