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.