CSS Selectors

Class Selectors

Browser compatibility
Chrome Firefox (Gecko) Internet Explorer Opera Safari
All All All All All

Class selectors match elements based on the contents of an element’s class attribute. The class selector .author, for example, would match any HTML element with the class attribute of “author.” The specific nature of class selectors combined with the ability to apply class attributes to any element makes them an extremely powerful and flexible option for styling. Because they are so easy to use class selectors can occasionally be over-used, resulting in non-semantic code and code that is more difficult to maintain.

Syntax

Class selectors are written by adding a period (‘.’) prior to the contents of the targeted attribute value, with no whitespace between the two. To make a class selector specific to an element type, add the element type prior to the period with no whitespace. The selector p.summary would match any paragraph with the class attribute of “summary”. Although CSS is not case-sensitive, there are certain use-cases where the styled document may parse classes with case sensitivity. Because of this it’s a good practice to match the case of class values.


.warning {
  color: red;
    }
    
h1.warning {
  color: red;
    }

Class selector syntax

Example:

Targeting class attributes

In this example I want to target specific class attribute values. Note how the styling is applied regardless of element type. Class selectors are also more specific than element selectors, so they allow us to overwrite the more general styles of element selectors.

Using class selectors

They also allow us to target very specific locations or instances by simply applying a class attribute. This is a great way to write styles for specific purposes with a single selector and then apply it whenever needed by adding the appropriate class attribute.

Care should be taken when using class selectors as overuse of them can bloat code and create stylesheets that are hard to maintain.