Lesson 2 / 1217%

Lesson 2

CSS Selectors

20 min

Target elements by tag, class, ID, or attribute.

What is a selector?

A CSS rule always consists of two parts: a selector, which designates which elements of the page are concerned, and a declaration block, placed between curly braces, which describes how those elements should be formatted. Without a selector, the browser doesn't know what to apply your styles to: it is therefore the basic building block of the whole language.

Each declaration is made of a property and a valueseparated by a colon, and ended by a semicolon. A well-chosen selector lets you target exactly what you want, no more, no less: that is the whole art of CSS.

rule-anatomy.css
/* selector  { property: value; } */
p {
  color: #334155;      /* one declaration */
  font-size: 18px;     /* another declaration */
}
  • p — the selector: it designates all the paragraphs.
  • color — the property: what you want to change.
  • #334155 — the value: the new setting applied.

The tag selector

The simplest selector directly targets a type of HTML tag: it applies to all the elements of that type on the page. It is also called an "element selector" or "type selector". You just write the name of the tag, without angle brackets.

It is ideal for defining the general appearance of a site: text color, heading font, list spacing. Its flaw is its lack of finesse: on its own, it is impossible to tell two paragraphs apart.

tag-selector.css
p {
  color: #334155;
}

h2 {
  color: #6d28d9;
}
tag-selector.html
<h2>A purple heading</h2>
<p>This paragraph is slate gray.</p>
<p>This one too: the rule targets all p tags.</p>

The universal selector

The asterisk * targets absolutely allthe elements of the page, whatever their type. It is mostly used at the very start of a stylesheet, to reset margins or to change the box model. Use it sparingly, because it affects everything.

universal-selector.css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

The class selector

A class (. followed by the name) targets only the elements that carry it, via the class attribute in HTML. The same element can have several classes, and a class can be reused on several elements.

To give an element several classes, you separate them with spaces in the attribute's value. The browser then applies all the matching rules, which lets you compose styles like building blocks: one class for color, another for size, another for spacing.

class-selector.html
<p class="alert">Attention, this is important.</p>
<p class="alert subtle">A more subtle message.</p>
<p>A normal, unstyled paragraph.</p>
class-selector.css
.alert {
  color: #b91c1c;
  font-weight: bold;
}

.subtle {
  font-size: 14px;
  opacity: 0.8;
}
Class selectors applied to paragraphs

You can also restrict a class to a specific type of tag by attaching them, with no space: p.alert only targets paragraphs with the alert class, whereas a div carrying the same class would remain untouched. And by attaching two classes, .alert.subtle, you only target elements that have both at the same time.

specific-class.css
/* Only <p> elements that have the "alert" class */
p.alert {
  border-left: 4px solid #b91c1c;
  padding-left: 12px;
}

/* Only elements that have "alert" AND "subtle" */
.alert.subtle {
  color: #9a3412;
}

The id selector

An id (# followed by the name) targets a single element on the page — an id must never be duplicated. It also serves as a target for anchor links (#my-id) and for JavaScript.

If two elements carry the same id, the HTML becomes invalid and the browser's behavior is no longer guaranteed: JavaScript, for example, will only find the first of the two. So reserve ids for what is truly unique: the main header, the footer, the main content area.

id-selector.html
<header id="main-header">
  <h1>My site</h1>
</header>

<a href="#main-header">Back to top</a>
id-selector.css
#main-header {
  background-color: #1e1b4b;
  color: white;
}

Best practice

In practice, we prefer to style with classes rather than ids: they are reusable and have a lower priority in the cascade, so they are easier to override later. Reserve ids for JavaScript or navigation anchors.

Combining selectors

Simple selectors become very powerful when you assemble them. The symbols that link them are called combinators: they express a relationship between elements (parent, child, neighbor) to target precisely, without multiplying classes.

combinations.css
/* Grouped selector: applies the same style to several selectors */
h1, h2, h3 {
  font-family: Georgia, serif;
}

/* Descendant selector: targets an <a> inside .nav, at any level */
.nav a {
  text-decoration: none;
}

/* Child selector: targets a <li> that is a direct child of .menu (not a grandchild) */
.menu > li {
  margin-right: 12px;
}

/* Adjacent selector: targets the <p> immediately following an <h2> */
h2 + p {
  margin-top: 0;
}

/* Attribute selector: targets inputs whose type is "email" */
input[type="email"] {
  border-color: #6d28d9;
}
  • A, B — group: applies the same style to A and B.
  • A B (space) — descendant: B inside A, whatever the nesting level.
  • A > B — direct child: B directly inside A.
  • A + B — adjacent: B right after A, same parent.
  • A ~ B — general sibling: all the B elements that follow A, same parent, not necessarily right next to it.
  • A[attr="value"] — attribute: targets A elements having this attribute with this value.

To clearly see the difference between "descendant" and "direct child", let's take a navigation menu with a nested submenu. The rule .menu li affects all list items, submenu included, whereas .menu > li only affects those of the first level.

descendant-vs-child.html
<ul class="menu">
  <li>Home</li>
  <li>
    Courses
    <ul>
      <li>HTML</li>
      <li>CSS</li>
    </ul>
  </li>
</ul>
descendant-vs-child.css
/* All <li> elements, including HTML and CSS in the submenu */
.menu li {
  color: #334155;
}

/* Only "Home" and "Courses" */
.menu > li {
  font-weight: bold;
}

Pseudo-classes

A pseudo-class, introduced by a colon, targets an element according to its state or its position, which HTML alone cannot express: the mouse hover, keyboard focus, the first child of a list. It is attached to the selector it refines, with no space.

pseudo-classes.css
/* State: on mouse hover */
a:hover {
  color: #6d28d9;
}

/* State: field selected with the keyboard */
input:focus {
  outline: 2px solid #6d28d9;
}

/* Position: first and last child */
li:first-child {
  font-weight: bold;
}

li:last-child {
  margin-bottom: 0;
}

/* Position: every other element (table rows, lists) */
tr:nth-child(even) {
  background-color: #f5f3ff;
}

Pseudo-elements

A pseudo-element, introduced by two colons, targets a part of an element, such as its first line, or creates decorative content that doesn't exist in the HTML. With ::before and ::after, the content property is required, otherwise nothing is displayed.

pseudo-elements.css
/* Adds an icon before each alert */
.alert::before {
  content: "⚠ ";
}

/* Formats only the first line of a paragraph */
p::first-line {
  font-variant: small-caps;
}

/* Changes the color of the text selection */
::selection {
  background-color: #ddd6fe;
}

Specificity (rule priority)

When several rules target the same element, CSS calculates the specificity of each selector to decide which one wins. From lowest to highest priority:

  1. Tag selector (p) — lowest priority
  2. Class, attribute, pseudo-class (.alert, :hover)
  3. Id (#header)
  4. Inline style (style="...")
  5. !important — overrides everything, avoid except in an emergency
specificity.css
p { color: blue; }        /* low specificity */
.text { color: green; }   /* beats "p" */
#unique { color: red; }   /* beats ".text" */

/* On <p class="text" id="unique">, the text will be red */

At equal specificity, the rule declared last in the CSS file wins — this is the "cascade" part of the name CSS.

Calculating specificity step by step

Specificity can be represented by three counters, written in the order (ids, classes, tags). You count the ids, then the classes, attributes and pseudo-classes, then the tags and pseudo-elements. You then compare the counters from left to right: a single id always beats any number of classes.

specificity-calculation.css
p                    /* (0, 0, 1) */
.alert               /* (0, 1, 0) */
p.alert              /* (0, 1, 1) */
.nav a:hover         /* (0, 2, 1): one class + one pseudo-class + one tag */
#header              /* (1, 0, 0) */
#header .nav a       /* (1, 1, 1) */

Inheritance

Some properties, like color or font-family, are inherited: if you define them on a parent, its children receive them automatically. Others, like border or margin, are not. Inheritance saves you from repeating the same rules everywhere and explains why a style set on body ends up on the whole page.

inheritance.css
body {
  font-family: system-ui, sans-serif;  /* inherited by all elements */
  color: #334155;                      /* inherited too */
}

.card {
  border: 1px solid #ddd6fe;           /* not inherited: only .card has a border */
}

Exercise

On a page with 3 paragraphs, give a .important class to one of them and style it differently from the other two (color, bold). Then add a unique id to a heading and style it too.

Going further

Deliberately create a conflict: give an element both a class and an id that define a different color. Check in the browser which one is displayed, and explain why based on specificity. Finally, calculate the three counters (ids, classes, tags) of each of your selectors to confirm your reasoning.