Open In App

How to apply CSS style to the different elements having same class name in HTML ?

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, We will learn to apply CSS style to the different elements having the same class name in the HTML. The class attribute is used to create a class for the HTML element and multiple elements can have the same class. The class name is often used to apply CSS style and also used in javascript to manipulate elements. The CSS class selector “.” (dot) is used to do our required tasks for the specific class. 

Let’s apply the CSS style to the different elements having the same class,

Approach 1: We will use the CSS class selector followed by the class name to apply the style to the different elements having the same class name.

Syntax:

 .classname1 {
       /*properties*/
}

Example: In this example, we are using the above-explained approach.

HTML




<!DOCTYPE html>
<html>
<head>
    <style>
        .gfg {
            text-align:center;
            color: green;
        }
 
        .geeks{
            background-color: black;
            text-align:center;
            font-style: italic;
            color: pink;
        }
    </style>
</head>
 
<body>
    <h1 class="gfg">GeeksforGeeks</h1>
    <h2 class="geeks">An example for the same class</h2>
    <div class="gfg">
        <p>GeeksforGeeks: A computer science portal</p>
    </div>
</body>
</html>


Output:

 

Here, We can observe that h1 and div have the same class, and when we apply the CSS style to the class “gfg”, the styles of h1 and div change together. This approach is often used when we want a similar style to different elements. 

Approach 2: If we want to apply the different CSS styles to the different elements having the same class then we can use another approach of the “.” CSS class selector. This approach is mostly recommended as it specifies the elements separately.

Syntax:

element_name.class_name{
    /*properties*/
}

Example: In this example, we are using the above-explained approach.

HTML




<!DOCTYPE html>
<html>
<head>
    <style>
        h1.gfg {
            text-align: center;
            color: green;
        }
 
        div.gfg {
            text-align: center;
            color: green;
            background-color: aqua;
        }
 
        .geeks {
            background-color: black;
            text-align: center;
            font-style: italic;
            color: pink;
        }
    </style>
</head>
 
<body>
    <h1 class="gfg">
        GeeksforGeeks
    </h1>
    <h2 class="geeks">An example for the same class</h2>
    <div class="gfg">
        <p>GeeksforGeeks: A computer science portal</p>
    </div>
</body>
</html>


Output:

 

Here, h1 and div have different background colors irrespective of having the same class.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads