Mastering the HTML `class` Attribute: Styling and Grouping HTML Elements

Learn how to effectively use the HTML `class` attribute to group and style HTML elements. This tutorial explains how to assign class names, apply styles using CSS, and utilize multiple classes for flexible and efficient web design.



Understanding the HTML `class` Attribute

Using the `class` Attribute

The HTML class attribute assigns one or more class names to an HTML element. This is a way to group elements together. This attribute is used extensively in conjunction with CSS (Cascading Style Sheets) and JavaScript to style and manipulate elements. Multiple elements can share the same class name. Class names are case-sensitive.

Applying Styles with the `class` Attribute and CSS

The class attribute is frequently used to apply styles defined in a CSS stylesheet. In the example below, all elements with the class "city" will share the same styling.

Example: Styling with Class and CSS

<p class="city">London</p>
<p class="city">Paris</p>
<p class="city">Tokyo</p>

<style>
.city {
  color: blue;
}
</style>

Multiple Classes per Element

An element can have multiple classes. Separate class names with a space.

Example: Multiple Classes

<p class="city main">London</p>

In this example, the paragraph will be styled according to both the city and main class definitions in the CSS.

Sharing Classes Across Elements

Different elements can use the same class name, enabling efficient styling of diverse elements with similar styles.

Example: Shared Classes

<h1 class="city">Paris</h1>
<p class="city">Paris is the capital of France</p>

Using the `class` Attribute with JavaScript

The class attribute is also useful with JavaScript. The getElementsByClassName() method lets you access all elements with a specific class name.

Example: JavaScript and Class

document.getElementsByClassName("city");

Class Selector Syntax in CSS

A class selector in CSS starts with a period (.) followed by the class name enclosed in curly braces {}, where you define the styles.

Example: Class selector Syntax

.city {
  color: blue;
}

Summary

The HTML class attribute is a versatile tool for styling and manipulating HTML elements using CSS and JavaScript. It allows for grouping and efficient management of elements, improving the organization and structure of your HTML. This enables efficient control of style, accessibility, and interactive features of your web page.