Class

Avatar of Sara Cope
Sara Cope on (Updated on )

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

A class selector in CSS starts with a dot (.), like this:

.class {

}

A class selector selects all elements with a matching class attribute.

For example, this element:

<button class="big-button">Push Me</button>

is selected and styled like this:

.big-button {
  font-size: 60px;
}

You can give a class any name that starts with a letter, hyphen (-), or underscore (_). You can use numbers in class names, but a number can’t be the first character or the second character after a hyphen. Unless you get crazy and start escaping selectors, which can get weird:

.\3A \`\( { 
  /* matches elements with class=":`(" */
} 

An element can have more than one class:

<p class="intro blue">
  This paragraph will get styles from .intro and .blue selectors.
</p>

An element with multiple classes is styled with the CSS rules for each class. You can also combine multiple classes to select elements:

/* only selects elements with BOTH of these classes */
.intro.blue {
    font-size: 1.3em;
 }

This demo shows how single-class selectors are different from combined selectors:

You can also limit a class selector to a specific kind of element, which is sometimes called “tag qualifying”:

ul.menu {
  list-style: none;
}

Specificity

By itself, a class selector has a specificity value of 0, 0, 1, 0. That’s “more powerful” than an element selector (like: a { }) but less powerful than an ID selector (like #header { }). Specificity increases when you combine class selectors or limit the selector to a specific element.

Accessing Classes with JavaScript

You can read and manipulate an element’s classes with classList in JavaScript. For instance, adding a class could be like:

document.getElementById('italicize').classList.add('italic'); 

This demo shows basic examples of classList in use:

jQuery also has methods for interacting with classes, including .addClass(), .removeClass(), .toggleClass(), and .hasClass().

More Information

Browser Support

ChromeSafariFirefoxOperaIEAndroidiOS
AnyAnyAnyAnyAnyAnyAny