CSS Class Selectors

CSS classes give you extra flexibility for specifying which elements are to receive a particular style.

A few lessons ago, we learned about selectors. You may recall that selectors are the things we apply a style against. In our examples, our selectors were all HTML elements. For example, we decided to make the <h1> element blue.

Now, that works well if you want all headings to be blue. But what if you only want some of your headings to be blue? Perhaps you want the color of your headings to reflect the section of the site that you're in.

Sounds like you need to use classes!

In CSS, classes allow you to apply a style to a given class of an element. To do this, you link the element to the style by declaring a style for the class, then assigning that class to the element.

CSS Class Syntax

You declare a CSS class by using a dot (.) followed by the class name. You make up the class name yourself. After the class name you simply enter the properties/values that you want to assign to your class.

If you want to use the same class name for multiple elements, but each with a different style, you can prefix the dot with the HTML element name.

For example:

CSS Class Example

You can also select elements (or classes) that's nested within another element or class. For example, div.css-section p will select all <p> elements that are nested within a <div> element that uses the .css-section class.

One major benefit of doing this is that you don't need to apply a class to every instance of an element when it's nested within another element that uses a class.

Here's an example: