It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

Use CSS Class for Styling Elements With Matching Class Attributes

Reading time 2 min
Published Sep 9, 2019
Updated Oct 9, 2019

TL;DR – CSS class refers to a selector that lets you select HTML elements according to their class attribute.

The use of classes

Class selectors get elements by class and let you style them with CSS properties. If a class applies to several elements, then CSS styles them the same.

You need to separate multiple classes in CSS by leaving space between them. Elements with several classes get styles of both.

Adding classes to elements

You can define CSS classes with a dot (.). Before you can select which class to style, you need to assign a specific HTML class attribute to elements first:

Example
<div class="example1">I am a div element that has a specific class attribute. Want to style me?</div>

If you have a couple of <div> elements that need to have different styling properties, you should give them individual classes:

Example
<div class="example1">I am a div element that has a specific class attribute. Want to style me?</div>
<div class="example2">I am another div and I might have other properties.</div>
<div class="example3">What about me?</div>
<div class="example4">Hey, and me?</div>

Then, you select each <div> class, add the dot as a prefix and set the necessary CSS properties.

Note: the same CSS classes can apply to multiple HTML elements, meaning that they will be styled the same.

Names of CSS classes can have letters, underscores, hyphens, and numbers. However, you should not include numbers as the first or the second characters after a hyphen.

Setting multiple classes

Elements can have multiple classes in CSS. You can assign two classes to elements by leaving space between them. As a result, CSS styling properties of both classes apply to such elements.

This example sets two <div> classes to make sure that all elements have one identical property of background-color while setting different CSS rules for them as well:

Example
<div class="example1">I am a div element that has a specific class attribute. Want to style me?</div>
<div class="example1 example2">I am another div and I might have other properties.</div>
<div class="example1 example3">What about me?</div>
<div class="example1 example4">Hey, and me?</div>

CSS class: useful tips

  • Other options for selecting which elements to style include finding elements by their attributes, and IDs.
  • You can use combinations of ID, attribute and class selectors to target elements even more accurately.