class
A list of class names that CSS and JavaScript use to find an element.
- Applies to
- All HTML elements
Example
#<style>
.card { padding: 12px 16px; border-radius: 12px; border: 1px solid #333; }
.card-highlight { border-color: #a78bfa; background: #1e1533; }
</style>
<p class="card">A regular card</p>
<p class="card card-highlight">A card highlighted with two classes</p>Definition and usage
#The class attribute assigns an element one or more class names, separated by spaces. Classes alone change nothing about how an element looks. They only gain meaning when you refer to them in CSS (the .name selector) or in JavaScript.
The same class can appear on many elements, and one element can have many classes. This lets you combine styles like building blocks: class="btn btn-primary btn-large" is a button with the shared look, the primary color, and a large size.
In JavaScript, the most convenient way to manage classes is element.classList: the add(), remove(), toggle() and contains() methods save you from gluing strings together by hand.
Syntax
#<element class="name another-name">β¦</element>Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Name classes after their role, not their looks:
.alert-errorsurvives a color change,.red-textdoes not. - Case matters:
Cardandcardare two different classes.
Related entries
#- class vs idclass can repeat across many elements and combine several at once. id must be unique across the whole document and is used for anchors, labels and JS.
- idA unique identifier for an element across the whole document.
- styleCSS styles written directly on an element.
- data-*Custom attributes for storing data for scripts and styles.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.