HTML Classes | Grouping and Styling Elements

HTML Classes allow you to assign a common identifier to multiple HTML elements. They are widely used in web development to style groups of elements with CSS and manipulate them using JavaScript.

Using Classes in HTML:

Classes are defined using the `class` attribute within an HTML tag. A single class can be applied to multiple elements, and an element can have multiple classes.

Basic Example of HTML Classes

<!DOCTYPE html>
<html>
<head>
<title>HTML Classes Example</title>
<style>
    .highlight {
        color: white;
        background-color: #4682b4;
        padding: 10px;
        border-radius: 5px;
    }
</style>
    </head>
    <body>
        <p class="highlight">This paragraph has the 'highlight' class applied.</p>
        <p>This paragraph does not have any class applied.</p>
    </body>
</html>

Using Multiple Classes:

An element can belong to multiple classes by separating class names with a space:

Code Example


<!DOCTYPE html>
<html>
<head>
<title>Multiple Classes Example</title>
<style>
    .bold {
        font-weight: bold;
    }
    .highlight {
        color: white;
        background-color: #4682b4;
    }
</style>
</head>
<body>
<p class="bold highlight">This paragraph has both 'bold' and 'highlight' classes applied.</p>
</body>
</html>

Output

This paragraph has both 'bold' and 'highlight' classes applied.

Benefits of Using Classes:

Best Practices:

HTML Classes are fundamental to creating well-structured and maintainable web pages. Start by experimenting with basic classes and gradually incorporate advanced combinations for complex designs.