✔ In HTML, a class is an attribute used to apply CSS styles or perform JavaScript actions on multiple elements at once.
✔ A class allows you to group elements under a single name and style them together.
✔ The class attribute is written as:
<class="classname">
✔ Multiple elements can share the same class, making it reusable.
<tag class="classname">Content</tag>
✔ The class
attribute is added inside any HTML tag.
✔ The classname is used in CSS or JavaScript for styling or functionality.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.highlight {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<p class="highlight">This is an important message.</p>
<p>This is a normal paragraph.</p>
</body>
</html>
✔ The class .highlight
applies red color and bold text only to the first paragraph.
A class can be applied to multiple elements for consistent styling.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box {
width: 150px;
height: 100px;
background-color: lightblue;
text-align: center;
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</body>
</html>
✔ All three <div>
elements have the same class .box
, applying the same styling.
You can assign multiple classes to a single element by separating them with spaces.
<p class="highlight large-text">This is an important and large message.</p>
.highlight {
color: red;
font-weight: bold;
}
.large-text {
font-size: 20px;
}
✔ The element will receive styles from both .highlight
and .large-text
classes.
Classes can also be used in JavaScript to dynamically change styles.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.active {
color: white;
background-color: green;
padding: 5px;
}
</style>
<script>
function addClass() {
document.getElementById("myText").classList.add("active");
}
</script>
</head>
<body>
<p id="myText">Click the button to add a class.</p>
<button onclick="addClass()">Apply Class</button>
</body>
</html>
✔ Clicking the button adds the "active" class to the paragraph, changing its style.
✅ Use meaningful class names (e.g., .error-message
, .nav-bar
).
✅ Follow CSS naming conventions (e.g., .btn-primary
, .card-header
).
✅ Use multiple classes to separate concerns (.text-bold .large-font
).
✅ Avoid too many classes on a single element (keep it simple).
@asadmukhtar