HTML Classes
On this page
HTML class Attribute
The class attribute is used to assign a class name to an HTML element.
Multiple HTML elements can share the same class.
The class Attribute
The class attribute is commonly used to apply CSS styles or to access elements with JavaScript.
Elements that share the same class name can be styled together.
<div class="city"> <h2>London</h2> <p>London is the capital of England.</p> </div> <div class="city"> <h2>Paris</h2> <p>Paris is the capital of France.</p> </div>
Using class on Inline Elements
The class attribute can be used on inline elements such as <span>.
<p>This is <span class="note">important</span> text.</p>
Class Syntax
To define a class in CSS, use a period (.) followed by the class name.
.city { background-color: tomato; color: white; padding: 10px; } The class name is then added to HTML elements using the class attribute.
<h2 class="city">London</h2> <h2 class="city">Paris</h2>
Multiple Classes
An HTML element can have more than one class.
Multiple class names are separated by a space.
<h2 class="city main">London</h2> <h2 class="city">Paris</h2>
Different Elements, Same Class
Different HTML elements can share the same class name.
<h2 class="city">Paris</h2> <p class="city">Paris is the capital of France.</p>
Using class with JavaScript
JavaScript can access elements by class name using getElementsByClassName().
var elements = document.getElementsByClassName("city"); Chapter Summary
- The
classattribute assigns one or more class names to an element - Multiple elements can share the same class
- Classes are used by CSS and JavaScript
- Class names are case sensitive
HTML Attributes
| Attribute | Description |
|---|---|
class | Specifies one or more class names for an element |