Free beginner tutorial

CSS Selectors: Element, Class and ID

A CSS selector identifies which HTML elements receive a style. Learning element, class and ID selectors gives you the basic tools for styling a page.

Element selectors

Select every element of a type by writing its tag name. This rule gives all paragraphs the same line height:

p {
  line-height: 1.7;
}

Class selectors

Use a class when a style should apply to a chosen group of elements. In CSS, a class name begins with a period.

.notice {
  padding: 1rem;
  background-color: #fff4e9;
}

Add the class to HTML with the class attribute: <p class="notice">Remember to save your work.</p>

ID selectors

An ID selector begins with # and targets an element whose id matches. An ID should be unique on the page; use a class when you need to style a reusable group.

#page-title {
  color: #203044;
}

Match it to an HTML id attribute:

<h1 id="page-title">My page</h1>

Combine selectors thoughtfully

Use classes for reusable styling. A selector such as .card h2 targets headings inside elements with the card class. Clear, simple selectors make a stylesheet easier to maintain.

Group selectors when styles are shared

Separate selectors with commas to give different elements the same declarations. This keeps repeated rules together:

.notice,
.warning {
  border-left: 4px solid #a74800;
  padding: 1rem;
}

Select elements by their relationship

A space matches a descendant at any depth. The child combinator > matches only direct children:

/* Every link inside the navigation, including nested lists */
nav a {
  color: #203044;
}

/* Only links that are direct children of the navigation */
nav > a {
  font-weight: 700;
}

Choose the relationship that matches your markup. A selector that is too broad can style nested elements you did not intend to change.

Use attribute selectors for specific controls

Square brackets match an attribute and, optionally, its value. For example, this rule targets email inputs without adding another class:

input[type="email"] {
  max-width: 32rem;
}

For interactive states such as a hovered link or a focused input, use a pseudo-class such as :hover or :focus-visible. The pseudo-classes lesson covers those states in more detail.