Open In App

How to apply styles to multiple classes at once ?

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Applying styles to multiple classes at once means using a single CSS rule to style multiple elements that share different class names. This can be achieved by separating class selectors with commas, allowing for efficient styling of various elements without redundant code.

Here we have some common approaches to applying styles to multiple classes at once:

Approach 1: Using Comma Separation

The Comma Separation approach in CSS allows you to apply the same styles to multiple classes by listing them together and separating them with commas. This method ensures different elements with distinct class names share the same styling properties efficiently.

Syntax:

.class_A , .class_B{
    /*property*/
}

Example 1: In this example we use the comma separation approach to apply the same styles (green color and 50px font size) to both .abc and .xyz classes, simplifying the styling process.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            background-color: black;
            color: white;
        }

        .abc,
        .xyz {
            color: green;
            font-size: 50px;
        }
    </style>

</head>

<body>
    <center>
        <h1 class="color-fg-success"> GeeksforGeeks </h1>
        <h3>How can I apply styles to multiple classes at once ?</h3>

        <div class="abc">GeeksforGeeks</div>
        <div class="xyz">GeeksforGeeks</div>

    </center>
</body>

</html>

Output:

Approach 2: Element Name and Class Name Combination

The Element Name and Class Name Combination approach targets specific elements with the same class by combining the element's name with the class selector. This method allows for more granular styling, applying styles only to particular elements with that class.

Syntax:

element_name.class_Name, element_name.class_Name, element_name.class_Name, {
    /*property*/
}

Note: This approach is mostly used to apply different CSS styles when the same class name is available in the different elements.

Example : In this example we use the Element Name and Class Name Combination approach to apply styles (green color and 50px font size) only to div elements with the .abc and .xyz classes, ensuring targeted styling.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            background-color: black;
            color: white;
        }

        div.abc,
        div.xyz {
            color: green;
            font-size: 50px;
        }
    </style>

</head>

<body>
    <center>
        <h1 class="color-fg-success"> GeeksforGeeks </h1>
        <h3>How can I apply styles to multiple classes at once ?</h3>

        <div class="abc">GeeksforGeeks</div>
        <div class="xyz">GeeksforGeeks</div>

    </center>
</body>

</html>

Output:


Next Article

Similar Reads