The class attribute lets you group HTML elements under a common name so they can share styles and behaviors. Classes are especially useful when you want to apply the same design to multiple elements without repeating inline styles. They can also be used in JavaScript to select and manipulate groups of elements.
<p class="highlight">This is a highlighted paragraph.</p>In the example above, the highlight class can be targeted in CSS to change its appearance or in JavaScript to apply dynamic effects.
One of the biggest advantages of classes is reusability. You can apply the same class name to multiple HTML elements, allowing them to share a consistent style or functionality. This reduces repetition in your CSS and makes your code more maintainable.
<h2 class="blue-text">Title</h2>
<p class="blue-text">Paragraph</p>Both the heading and paragraph in this example have the blue-text class, so they will be styled the same way in CSS without duplicating style rules.
In CSS, class selectors start with a dot (.) followed by the class name. Any element with that class will inherit the styles you define. This makes it easy to consistently style multiple elements with a single rule.
.blue-text {
color: blue;
padding: 10px;
}In this example, any element with the blue-text class will have blue text and 10px of padding applied.
An element can belong to more than one class by listing the class names separated by spaces. This is helpful when you want to combine multiple style rules or behaviors for the same element.
<div class="alert bold">Warning message!</div>.alert {
color: red;
}
.bold {
font-weight: bold;
}Here, the <div> element is both alert and bold, meaning it will be styled as red text and bold font weight by combining both class rules.
JavaScript can select elements by class name to change their style, add effects, or handle events dynamically. The document.getElementsByClassName() method returns a live HTMLCollection of all matching elements.
const notes = document.getElementsByClassName("note");
for (let item of notes) {
item.style.backgroundColor = "lightyellow";
}In this example, every element with the note class will have its background color changed to light yellow using JavaScript.
Create a heading, paragraph, and div that all use the "shared-style" class. Use CSS to give them blue text and padding. This exercise helps you see how one class can control multiple elements’ styling in one place.
<h2 class="shared-style">Heading</h2>
<p class="shared-style">This is a paragraph.</p>
<div class="shared-style">This is a div.</div>
<style>
.shared-style {
color: blue;
padding: 10px;
}
</style>Ask the AI if you need help understanding or want to dive deeper in any topic