The class attribute lets you group HTML elements and assign specific styles or behaviors to them. It's essential for using CSS and JavaScript effectively.
A class is a name you assign to an element. Based on this name, the element can be associated with one or more styles or functions. You can reference it in your CSS or JavaScript code.
html
<p class="highlight">This is a highlighted paragraph.</p>
The class attribute allows you to assign the same style or behavior to multiple similar elements β for example, to give several boxes the same appearance.
html
<div class="card">
<h2 class="card-title">Product Title</h2>
<p class="card-description">Short product description.</p>
</div>
You can assign multiple classes to a single HTML element by separating them with spaces. This way, a paragraph can be both red and bold, for instance.
html
<p class="text-bold text-red">Important message</p>
The class attribute is reusable β you can apply it to many elements without repeating styles manually, which makes your code more efficient and consistent.
Use meaningful, clear names for classes, like .nav-bar or .card-title. Avoid vague or overly generic names.
html
<div class="navigation-bar">
<a class="nav-item" href="#">Home</a>
<a class="nav-item" href="#">About</a>
</div>
The main purpose of the class attribute is to link HTML with CSS. If a class name matches one defined in the CSS file, the element will automatically adopt the defined styles.
html
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
<p class="highlight">This paragraph is styled using a class.</p>
When you assign multiple classes to an element, it inherits styles from all of them. For example, a button can be large, colorful, and bordered β each class adds a different styling rule.
BEM (Block Element Modifier) is a popular naming convention for class names that promotes clarity and reusability. For example: card__title or card--featured. The double underscore is for elements, the double dash for modifiers.
html
<div class="card card--featured">
<h2 class="card__title">Article Title</h2>
<p class="card__text">Some text here.</p>
</div>
Avoid long or confusing class names. Stick to consistent naming (like kebab-case), and donβt use CSS reserved words. Think reusability β a well-named class can be applied across many components.
You can modify the class attribute using JavaScript. The classList object lets you add, remove, or check for classes on an element dynamically.
html
<script>
document.querySelector("p").classList.add("new-style");
</script>
Select Language
Set theme
Β© 2025 ReadyTools. All rights reserved.