class
A class
is an HTML attribute used to select one or more elements for CSS styling or JavaScript purposes.
For Styling
The class
attribute is used for assigning styles to elements. Multiple classes can be assigned to a single element in a space-separated list. (e.g. class="class1 class2 class3"
)
Inside the stylesheet, a class name is selected with the following syntax:
.class-1 {}
A class selector is a name preceded by a period (.
).
Below is some markup with the classes header-1
and P1
and P2
. Elements with the header-1
, P1
and P2
class names receive different styling.
<!DOCTYPE html><html lang="en"><head><style>.header-1 {background-color: lightblue;font-size: 40px;}.P1 {background-color: white;font-size: 25px;}.P2 {background-color: yellow;font-size: 20px;}</style><title>Classes</title></head><body><!--HEADER--><div class="title"><h1 class="header-1">PIZZA MAN</h1></div><!--HISTORY--><p class="P1">Pizza Man is a family-owned business since 1964. Our goal is to make thebest pizza and have it delivered to your place.</p><p class="P2">We have 3 locations so far and growing.</p></body></html>
The code above will result in an output in a browser similar to:
For JavaScript
The class
attribute is used to perform JavaScript operations on HTML elements. Through the Document Object Model (“DOM”) there are various JavaScript methods built for selecting elements via their class.
Assuming the markup from the last example is linked to a JavaScript file:
const innerDiv = document.getElementsByClassName('header-1')[0];console.log(innerDiv.textContent);
The code above selects the first element of a given class, and prints its content to the console.
'PIZZA MAN'
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn HTML on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly7 hours