Skip to the content

Lesson 15 of 296

How CSS works and selectors

What you will learn

  • What CSS is and how a CSS rule is written
  • The three ways to add CSS to a page
  • Selectors: how to choose which elements a rule styles
  • Combinators, pseudo-classes and pseudo-elements
  • A simple naming system for classes
On this page

What is CSS?

CSS (Cascading Style Sheets) is the language that describes how HTML should look. HTML says what something is. CSS says how it looks.

A CSS rule

h1 {
  color: navy;
  font-size: 32px;
}
PartNameMeaning
h1SelectorWhich elements to style
{ ... }Declaration blockThe styles to apply
colorPropertyWhat to change
navyValueThe new setting
color: navy;DeclarationOne property and its value. Ends with ;

Three ways to add CSS

1. External file (the normal way). Write CSS in a .css file and link it in the <head>:

<link rel="stylesheet" href="/css/style.css">

One file can style every page, and the browser can save (cache) it so later pages load faster.

2. Internal style tag. CSS inside a <style> element in the <head>. Fine for a single small page or a demo.

<style>
  p { color: grey; }
</style>

3. Inline style. CSS inside a style attribute on one element.

<p style="color: red;">Warning</p>

Avoid this. It cannot be reused, it mixes content and design, and it is hard to override (Lesson 16 explains why).

Basic selectors

SelectorExampleSelects
Element (type)pEvery <p>
Class.cardEvery element with class="card"
ID#headerThe one element with id="header"
Universal*Every element
Grouph1, h2, h3Every h1, h2 and h3
Attributeinput[type="email"]Inputs whose type is email

Use classes for almost all styling. They are reusable and easy to override. Avoid styling with ids, because their high priority makes later changes difficult.

Combinators: selecting by position

SelectorNameSelects
nav aDescendant (space)Every <a> anywhere inside a <nav>
ul > liChildOnly <li> elements directly inside a <ul>
h2 + pNext siblingThe first <p> that comes straight after an <h2>
h2 ~ pFollowing siblingsEvery <p> after an <h2>, with the same parent
<nav>
  <ul>
    <li><a href="/">Home</a></li>
  </ul>
</nav>

nav a matches the link, because it is somewhere inside nav. nav > a does not match it, because the link is not a direct child of nav.

Pseudo-classes: selecting by state

A pseudo-class starts with one colon. It selects an element when it is in a certain state or position.

Pseudo-classSelects
:hoverWhen the mouse is over the element
:focusWhen the element has keyboard focus
:focus-visibleFocus that should be shown, usually from the keyboard, not a mouse click
:activeWhile it is being clicked
:visitedA link the user has already visited
:disabled / :checkedDisabled fields / ticked checkboxes and radios
:first-child / :last-childThe first / last child of its parent
:nth-child(2)The 2nd child. :nth-child(odd) and :nth-child(even) also work.
:not(.active)Elements that do not match .active
a:hover { text-decoration: underline; }
button:focus-visible { outline: 3px solid orange; }
tr:nth-child(even) { background: #f5f5f5; }
li:not(:last-child) { border-bottom: 1px solid #ddd; }

Modern selectors: :is, :where and :has

:is(h1, h2, h3) a { color: teal; }

:is() is a short way to write a group. The line above means h1 a, h2 a, h3 a.

:where() does the same, but has zero priority, so it is easy to override (see Lesson 16).

.card:has(img) { padding: 0; }

:has() selects a parent based on what is inside it. This rule styles any .card that contains an image. Before :has(), CSS could not select a parent by its children at all.

Pseudo-elements: styling part of an element

A pseudo-element starts with two colons. It styles a part of an element, or adds content that is not in the HTML.

Pseudo-elementSelects
::beforeA made-up first child, used to add decoration
::afterA made-up last child
::placeholderThe placeholder text of a field
::first-line / ::first-letterThe first line / letter of text
::selectionText the user has highlighted
.required::after {
  content: " *";
  color: red;
}

::before and ::after only appear if they have a content property, even an empty one: content: "";.

Naming classes: BEM

On large projects, class names can clash. BEM (Block, Element, Modifier) is a popular naming system that keeps names clear:

.card              the block
.card__title       an element inside the block (two underscores)
.card--featured    a different version of the block (two hyphens)

You do not have to use BEM, but you should be able to explain it, and you should name classes by what they are (.price), not by how they look (.red-bold-text).

Common mistakes

  • Missing semicolon. The next declaration may be ignored.
  • Forgetting the dot or hash: card { } styles <card> elements, which do not exist. You need .card.
  • Confusing descendant and child: nav a and nav > a are different.
  • One colon vs two: :hover is a pseudo-class; ::before is a pseudo-element.
  • Styling with ids, then struggling to override them.

How to say it in an interview

"A CSS rule is a selector plus declarations, which are property-value pairs. I put CSS in external files and style mostly with classes, because ids have very high specificity. I use combinators like descendant and child, pseudo-classes for states like hover and focus-visible, and pseudo-elements like before and after for decoration. Newer selectors like has let me style a parent based on its content."

Key words

WordMeaning
SelectorThe part that chooses which elements a rule applies to
DeclarationOne property and its value
CombinatorA symbol that selects by relationship: space, >, +, ~
Pseudo-classA selector for a state or position, with one colon
Pseudo-elementA selector for part of an element, with two colons
BEMA naming system: block__element--modifier

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.