Grow your CSS skills. Land your dream job.

Class

Last updated on:

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:

See the Pen Using Multiple Classes in CSS by mariemosley (@mariemosley) on CodePen.

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:

See the Pen .classList demo by Chris Coyier (@chriscoyier) on CodePen.

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

More Information

Browser Support

Chrome Safari Firefox Opera IE Android iOS
Any Any Any Any Any Any Any

Comments

  1. 0, 0, 1, 0 ,

    Understanding Specification is very Important in CSS

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".