Giving an element a class

suggest change

Classes are identifiers for the elements that they are assigned to. Use the class attribute to assign a class to an element.

<div class="example-class"></div>

To assign multiple classes to an element, separate the class names with spaces.

<div class="class1 class2"></div>

Using classes in CSS

Classes can be used for styling certain elements without changing all elements of that kind. For example, these two span elements can have completely different stylings:

<span class="special"></span>

Classes of the same name can be given to any number of elements on a page and they will all receive the styling associated with that class. This will always be true unless you specify the element within the CSS.

For example, we have two elements, both with the class highlight:

<div class="highlight">Lorem ipsum</div>
<span class="highlight">Lorem ipsum</span>

If our CSS is as below, then the color green will be applied to the text within both elements:

.highlight { color: green; }

However, if we only want to target div’s with the class highlight then we can add specificity like below:

div.highlight { color: green; }

Nevertheless, when styling with CSS, it is generally recommended that only classes (e.g. .highlight) be used rather than elements with classes (e.g. div.highlight).

As with any other selector, classes can can be nested:

.main .highlight { color: red; } /* Descendant combinator */ 
.footer > .highlight { color: blue; } /* Child combinator */

You can also chain the class selector to only select elements that have a combination of several classes. For example, if this is our HTML:

<div class="special left menu">This text will be pink</div>

And we want to colour this specific piece of text pink, we can do the following in our CSS: { color: pink; }

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents