← Web basics: HTML, CSS and JavaScript

Selectors: element, class and id

Choose exactly which elements a rule styles.

Start this lesson

An element selector like p styles every paragraph. Often you want only some of them. A class lets you label any elements you choose: write class="sale" in the HTML and select them in CSS with a dot, .sale. An id names one single element: id="cart" in HTML and #cart in CSS. You can also combine selectors: "nav a" means links inside a nav, and "h1, h2" styles both. When two rules disagree, the more specific selector wins (id beats class, class beats element), and among equals the later rule wins.

<style>
  li { color: gray; }
  .sale { color: crimson; }
  #featured { font-weight: bold; }
</style>

<ul>
  <li>Socks</li>
  <li class="sale">Scarf</li>
  <li class="sale" id="featured">Gloves</li>
</ul>

Socks is gray. Scarf and Gloves have the class sale, which is more specific than li, so they are crimson. Gloves also has the id featured, so it is bold too.

One element can have several classes separated by spaces: class="sale new". Use classes much more often than ids; ids must be unique on the page.

Class names are case-sensitive and cannot contain spaces. Short, meaningful names like .card or .warning work best.