A class attribute assigns one or more classnames to an HTML element.
Each classname references a style that is defined in CSS.
The class attribute can be placed on any HTML element.
A <div> element with a class attribute.
<style>
.bg-blue {background-color:aliceblue; border:1px solid steelblue; padding:25px;}
</style>
<div class="bg-blue">
A div styled with a CSS class.
</div>
Note: Class names are prefixed with a dot (.) in CSS, but not when they are used in HTML.
A class can have any number of classnames.
Here is an example of a class attribute with two classnames.
<style>
.blue {background-color:aliceblue; border:1px solid steelblue; padding:25px;}
.text-italic { font-style: italic;}
</style>
<div class="blue text-italic">
A div element styled with two classnames.
</div>
Different tags and tag types can be assigned the same classname.
A <div> and a <p> tag using the same classname. They look the same.
A paragraph using the lavender classname for styling.
<style>
.lavender {background-color:lavender; border:1px solid teal; padding:25px;}
</style>
<div class="lavender">
A div element using the lavender classname for styling.
</div>
<p class="lavender">
A paragraph using the lavender classname for styling.
</p>
The class attribute can be used on any element, including inline elements, such as <span>.
A class on a <span> element. The classname highlights the word 'cancelled'.
<style>
.orange {color: orangered;}
</style>
<section>
Your order has been <span class="orange">cancelled</span>.
</section>
JavaScript can locate elements by class name using the getElementsByClassName()
method.
In this example, JavaScript locates and hides all elements with a classname js-paragraph
.
Clicking the button toggles the visibility of all paragraphs.
Paragraph about Vincent Van Gogh.
Paragraph about Paul Cézanne.
Paragraph about Henri Matisse.
<section>
<h5>About Van Gogh</h5>
<p class="js-paragraph">Paragraph about Vincent Van Gogh.</p>
<h5>About Cézanne</h5>
<p class="js-paragraph">Paragraph about Paul Cézanne.</p>
<h5>About Matisse</h5>
<p class="js-paragraph">Paragraph about Henri Matisse.</p>
<br />
<button onclick="toggle();">Toggle paragraphs</button>
</section>
<script>
let toggle = () => {
let titles = document.getElementsByClassName("js-paragraph");
for (let i = 0; i < titles.length; i++) {
titles[i].style.display = titles[i].style.display == "none" ? "block" : "none";
}
}
</script>
Tip: Classname js-paragraph
is not defined in CSS -- and is not used for styling.
Classnames that are only used for JavaScript DOM access are commonly prefixed with js-
, like js-paragraph
.