Classes and Ids

In HTML, the class and id attributes are utilized for styling and identifying elements. Classes can be reused, whereas IDs must be unique within a page.

HTML Classes & IDs

Classes and IDs are crucial attributes in HTML that help in styling and uniquely identifying elements with CSS and JavaScript. While both are used for element selection, they serve different functions and should be used accordingly.


HTML Classes

Purpose

Classes allow grouping multiple elements together, enabling shared styles and behavior across them.

Syntax

The class attribute can be assigned to any HTML element.

index.html
<tag class="classname"></tag>

Usage

Classes can be applied to multiple elements to maintain consistency in styling.

My Cities
London

London is the capital of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

index.html
<!DOCTYPE html>
<html>
<body>
<style>
.myHeader {
  background-color: lightblue;
  color: black;
  padding: 40px;
  text-align: center;
}

.city {
  background-color: tomato;
  color: white;
  padding: 10px;
}
</style>

<h1 class="myHeader">My Cities</h1>

<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>
</body>
</html>

Styling Elements with Classes

Using CSS, elements with the same class name can be uniformly styled.

My Important Heading

This is some important text.

<h1>My <span class="note">Important</span> Heading</h1>
<p>This is some <span class="note">important</span> text.</p>

Conclusion - Classes

The class attribute assigns one or more class names to an element.Used by CSS and JavaScript for styling and interaction.Multiple elements can share the same class.JavaScript can access elements with a class using getElementsByClassName().

HTML IDs

Purpose

IDs uniquely identify a single element within a page.

Syntax

The id attribute can be assigned to any HTML element.

index.html
<tag id="uniqueID"></tag>

Example

Below, the <p> element is assigned a unique ID, and its text color is modified using inline CSS.

This text is styled using the ID attribute.

index.html
<p id="my-paragraph" style="color: aqua;">
  This text is styled using the ID attribute.
</p>

Conclusion

class allow for grouping multiple elements and applying shared styles, making them useful for consistent styling across a page. id, on the other hand, are unique and target a single element, ensuring precise identification. class are reusable, while id must remain unique within the document.