HTML The class Attribute HTML
- HTML Introduction
- HTML Tags
- HTML Basic Examples
- HTML Headings
- HTML Paragraphs
- HTML Links
- HTML Images
- HTML Buttons
- HTML Lists
- HTML Attributes
- HTML Horizontal Rules
- The HTML <head> Element
- The HTML <pre> Element
- The HTML Style Attribute
- HTML Text Formatting
- HTML Quotation and Citation Elements
- HTML Comment Tags
- HTML Colors
- Styling HTML with CSS
- HTML Tables
- HTML Lists
- HTML The class Attribute
- HTML The id Attribute
- HTML Iframes
- HTML Form Elements
HTML The class Attribute
Using The class Attribute
The HTML class
attribute is used to define equal styles for elements with the same class name.
So, all HTML elements with the same class
attribute will get the same style.
Here we have three <div>
elements that point to the same class name:
Example
<!DOCTYPE html>
<html>
<head>
<style>
.cities {
background-color: black;
color: white;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div class="cities">
<h2>London</h2>
<p>London is the capital of England.</p>
</div>
<div class="cities">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
<div class="cities">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>
</body>
</html>
Using The class Attribute on Inline Elements
The HTML class
attribute can also be used on inline elements:
Example
<!DOCTYPE html>
<html>
<head>
<style>
span.note {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
<h1>My <span class="note">Important</span> Heading</h1>
<p>This is some <span class="note">important</span> text.</p>
</body>
</html>
Tip: The class
attribute can be used on any HTML element.
Note: The class name is case sensitive!
Select Elements With a Specific Class
In CSS, to select elements with a specific class, write a period (.) character, followed by the name of the class:
Example
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
Multiple Classes
HTML elements can have more than one class name, each class name must be separated by a space.
In the example above, the first <h2>
element belongs to both the "city" class and the "main" class.
Different Tags Can Share Same Class
Different tags, like <h2>
and <p>
, can have the same class name and thereby share the same style:
Using The class Attribute in JavaScript
The class name can also be used by JavaScript to perform certain tasks for elements with the specified class name.
JavaScript can access elements with a specified class name by using the getElementsByClassName()
method:
When a user clicks on a button, hide all elements with the class name "city":
<script>
function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>