HTML Classes - Detailed Overview

Introduction to HTML Classes

Classes in HTML are used to apply styles and manage elements using CSS and JavaScript. A class can be applied to one or multiple elements, and elements can have multiple classes.

Defining and Using Classes

To define a class in HTML, use the class attribute. The class name can then be referenced in your CSS or JavaScript. Here’s an example:

<div class="red-box">
    This is a red box.
</div>
<div class="blue-box">
    This is a blue box.
</div>
This is a red box.
This is a blue box.

Applying Multiple Classes

You can apply multiple classes to a single element by separating them with spaces. Here’s an example:

<div class="green-box styled-box">
    This box is green and has a standard styling.
</div>
This box is green and has a standard styling.

Styling Classes with CSS

In your CSS, you can style elements by referencing their class name with a dot (.) followed by the class name. For example:

.red-box {
    background-color: #e74c3c;
    padding: 10px;
    color: white;
    border-radius: 5px;
}

The above CSS code applies a red background, padding, white text color, and rounded corners to any element with the class red-box.

Using Classes with JavaScript

JavaScript can interact with classes to dynamically add, remove, or toggle classes on elements. For example:

<button onclick="toggleGreen()">Toggle Green Box</button>
<div id="toggleBox" class="styled-box">
    This box can turn green.
</div>

<script>
function toggleGreen() {
    document.getElementById("toggleBox").classList.toggle("green-box");
}
</script>
This box can turn green.