HTML classes are a fundamental attribute used to categorize and style elements in web development. They provide a way to apply consistent styling across multiple elements and enhance the structure of your HTML documents.
Classes in HTML are attributes that allow you to assign one or more labels to elements. These labels can be used to:
To add a class to an HTML element, use the class
attribute followed by the class name. Here's a basic example:
<p class="highlight">This paragraph has a class.</p>
You can also assign multiple classes to a single element by separating them with spaces:
<div class="container flex-box">This div has two classes.</div>
One of the most common uses of HTML classes is for applying CSS styles. Here's an example:
<!-- HTML -->
<p class="error-message">This is an error message.</p>
<!-- CSS -->
<style>
.error-message {
color: red;
font-weight: bold;
}
</style>
Classes can also be used to select elements for JavaScript manipulation:
<!-- HTML -->
<button class="toggle-btn">Toggle</button>
<div class="content">Content to toggle</div>
<!-- JavaScript -->
<script>
const toggleBtn = document.querySelector('.toggle-btn');
const content = document.querySelector('.content');
toggleBtn.addEventListener('click', () => {
content.classList.toggle('hidden');
});
</script>
While classes and HTML IDs serve similar purposes, they have key differences:
Classes | IDs |
---|---|
Can be used on multiple elements | Must be unique within a page |
Selected with a dot (.) in CSS | Selected with a hash (#) in CSS |
Lower specificity in CSS | Higher specificity in CSS |
HTML classes are a versatile tool for web developers. They provide a way to organize, style, and manipulate elements efficiently. By understanding and effectively using classes, you can create more maintainable and flexible web pages.
For more information on related topics, check out HTML attributes and HTML and CSS.