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.
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>
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>
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
.
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>