class
AttributeThe HTML class
attribute is one of the most versatile and commonly used attributes in web development. It allows developers to assign one or more class names to an HTML element, enabling grouping, styling, and dynamic behavior with CSS and JavaScript. The class
attribute is essential for building modern, responsive, and well-structured web pages.
class
Attribute?The class
attribute in HTML is used to assign a name (or multiple names) to an element. These names are used to group elements for styling purposes with CSS or to target them in JavaScript for scripting purposes.
class
Attribute
<element class="class-name">
Content goes here...
</element>
You can assign multiple classes by separating class names with a space.
<element class="class1 class2 class3">
Content goes here...
</element>
Tip: The class attribute can be used on any HTML element.
Note: The class name is case sensitive!
Tip: You can learn much more about CSS in our CSS Tutorial.
class
Attributeclass
Attribute in Actionclass
Attribute
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p class="highlight">This paragraph is highlighted.</p>
<p>This paragraph is not highlighted.</p>
</body>
</html>
<style>
.city {
color: red;
}
.main{
font-weight: bold;
}
</style>
<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.clicked {
color: green;
}
</style>
</head>
<body>
<p class="message">Click me to change color!</p>
<script>
document.querySelector('.message').addEventListener('click', function() {
this.classList.add('clicked');
});
</script>
</body>
</html>
Different HTML elements can point to the same class name.
In the following example, both <h2> and <p> point to the "city" class and will share the same style:
<h2 class="country">India</h2>
<p class="country">India one of the most beautifull country</p>
class
Attribute.button-primary
)..red
or .box
unless necessary..main-header
).class
attribute specifies one or more class names for an elementclass
attribute can be used on any HTML elementgetElementsByClassName()
methodclass
Attributeclass
attribute to an HTML element.<style>
block.class
Attributeid
and class
attributes?id
attribute is unique and can only be used once per page, while the class
attribute can be reused on multiple elements.class
attribute with inline styles?class
attribute and inline styles on the same element, though it is better to keep styling in CSS for maintainability.