start learning
Image 1
3HTMLClasses

HTML Classes

In HTML, classes are used to define groups or categories that can be applied to multiple elements on a webpage. A class is a way to identify and style specific elements or groups of elements with CSS (Cascading Style Sheets) or JavaScript.

By assigning the same class to multiple elements, you can easily apply consistent styles or behavior to those elements. For example, if you have several paragraphs that you want to have the same font style, you can assign them all the same class and define the desired font style in your CSS.

Classes are defined using the class attribute in HTML tags. Multiple classes can be applied to an element by separating them with spaces. For example :


<p class="highlighted">This is a highlighted paragraph.</p>

In this example, the class "highlighted" is applied to the <p> element. Then, in the CSS, you can define the styles for the "highlighted" class to make the text stand out.

HTML Classes example

<p class="highlight1">This is a highlighted paragraph.</p>
<p>This is a regular paragraph.</p>
<p class="highlight2">This is another highlighted paragraph.</p>

    .highlight1 {
        background-color: yellow;
    }
      .highlight2 {
        background-color: green;
    }

In this example, we have three <p> elements. The first and third paragraphs have the class "highlight1 " , "highlight2" applied to them and we're defining a style for the class "highlight1" that will give the elements a yellow background color and "highlight2" that will give the elements a green background color.

Preview :

This is a highlighted paragraph.

This is a regular paragraph.

This is another highlighted paragraph.



<p class="highlight special">This is a highlighted and special paragraph.</p>

    .highlight {
        background-color: yellow;
        color: red;
    }

    .special {
        font-weight: bold;
        text-decoration: underline;
    }

In this updated example, we've added a new style for the "special" class that will make the text bold and underlined.

Preview :

This is a highlighted and special paragraph.

By assigning both classes, we can combine the styles defined for each class.

That's it! You've gone through a step-by-step tutorial on using classes in HTML. Remember that classes provide a way to group elements and apply consistent styles or behavior. By defining CSS styles for classes, you can easily customize and manipulate elements on your webpage.


×