Loading
The class attribute in HTML is used to group elements and apply common CSS styles or JavaScript behaviors to them. It allows you to target elements efficiently without repeating styles individually.


Syntax:

<tag class="className">Content</tag>

To apply multiple classes:
<tag class="class1 class2"></tag>


Example: Styling with Class

<!DOCTYPE html>
<html>

<head>
    <title>Class Example</title>
    <style>
        .highlight {
            background-color: beige;
            color: rgb(203, 32, 9);
            padding: 10px;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <p class="highlight">This is a paragraph with a custom class applied.</p>
</body>

</html>

Output:

Uploaded Image




Using the Same Class Multiple Times

You can reuse a class on multiple elements to apply the same style uniformly.


Example:

<!DOCTYPE html>
<html>

<head>
    <title>Same Class Multiple Times</title>
    <style>
        .info {
            color: teal;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <p class="info">This is an info message.</p>
    <div class="info">This is another info section using the same class.</div>
</body>

</html>

Output:

Uploaded Image




Multiple Classes on a Single Element

You can also assign multiple classes to one element


Example:

<!DOCTYPE html>
<html>

<head>
    <title>Multiple Classes</title>
    <style>
        .box {
            border: 1px solid #333;
            padding: 10px;
        }

        .blue-text {
            color: blue;
        }
    </style>
</head>

<body>
    <div class="box blue-text">This box has multiple classes</div>


</body>

</html>

Output:

Uploaded Image




Class in JavaScript

JavaScript can select and manipulate class-based elements


Example:

<!DOCTYPE html>
<html>

<head>
    <title>Class in JavaScript</title>
    <script>
        function changeColor() {
            document.querySelector('.highlight').style.color = 'green';
        }
    </script>
</head>

<body>
    <p class="highlight">Click the button to change my color.</p>
    <button onclick="changeColor()">Change Color</button>
</body>

</html>

Output:

Uploaded Image




on clicking the button color of the paragraph will change

Uploaded Image




Tips

  • Avoid space inside a single class name (use hyphens or camelCase).
  • Prefer lowercase class names for consistency.
  • Use classes for reusability, and IDs (id=". . .") for uniqueness.


Key Point

  • A class can be assigned to any HTML tag.
  • Multiple elements can share the same class.
  • Multiple classes can be applied to a single element.
  • Class names are case-sensitive (.Highlight and .highlight are different). 
  • Classes are mainly used with CSS and JavaScript for styling and dynamic behavior.