Classes in CSS


CSS classes are used to select elements from the webpage and add style to them. Classes are used to add style to multiple elements at once.

The CSS classes allow us to define multiple CSS properties in a single block and when that class is added to any element then all the specified CSS property is reflected in the HTML element.

Classes are defined either in the style tag or in the external stylesheet.

Once a class is defined it can be used as many times as you want to use.

classes in CSS
Classes in CSS

Defining a class

Classes are defined using a dot (.) followed by the class name.

For example, if we want to define a class named myclass then we will write it as .myclass.

CSS properties for that class will be written inside the curly braces.

Note: The class name should not start with a number and should not contain spaces or special characters except the hyphen (-).

.class-1 {
    background-color: #182C61;
    margin: 10px;
    font-size: 20px;
}

.class-2 {
    color: #CAD3C8;
    padding: 25px;
}

Adding class to the element

Once a class is defined, it can be added to any element using the class attribute in the HTML element.

For example, if we want to add the class class-1 to the p element then we will write it as <p class="class-1">This is a paragraph</p>.

<p class="class1">Paragraph with single class</p>

Multiple classes can be added to an element. like shown below.

<p class="class1 class2 class3">Paragraph with multiple class</p>

A working example for CSS class.

Example

<style>
  .class-1 {
    background-color: #ea8a74;
    color: white;
    font-size: 20px;
    padding: 10px;
    width: 100%;
  }
</style>

<p class="class1">Paragraph with class-1</p>
<p class="class1">Paragraph with class-1</p>
<p class="class1">Paragraph with class-1</p>
Try it

Output:

Paragraph with class-1

Paragraph with class-1

Paragraph with class-1

Note: A class can be used multiple times in a single HTML document. And also an element can have multiple classes.