Skip to content

HTML Classes

The class attribute allows you to assign one or more class names to an HTML element. This is primarily used to target elements with CSS for styling or with JavaScript for manipulation.

You can apply the same CSS styles to multiple elements by giving them the same class name.

Imagine styling several information boxes consistently:

<div class="info-box">
<h2>London</h2>
<p>London is the capital city of England...</p>
</div>
<div class="info-box error">
<h2>System Alert</h2>
<p>An error occurred during the process.</p>
</div>
<div class="info-box success">
<h2>Update Complete</h2>
<p>Your profile has been updated successfully.</p>
</div>
/* Base style for all info boxes */
.info-box {
border: 1px solid #ccc;
margin: 20px;
padding: 15px;
background-color: #f9f9f9;
border-radius: 5px;
}
/* Specific style for error boxes */
.error {
border-left: 5px solid red;
background-color: #ffebeb;
}
/* Specific style for success boxes */
.success {
border-left: 5px solid green;
background-color: #e6ffed;
}

In this example:

  • All <div> elements with class="info-box" get the base styling.
  • The second <div> has two classes (info-box and error). It gets the base styles plus the specific error styles.
  • The third <div> has info-box and success classes, receiving base styles and success styles.
  • Multiple class names are separated by spaces within the class attribute.

The class attribute works just as well on inline elements like <span>, <a>, **, etc., allowing you to style specific parts of text.

Example: Highlighting text within a paragraph.

<h1>Product Announcement</h1>
<p>Please read the <span class="highlight-important">critical update notes</span> before proceeding.</p>
<p>Standard terms and conditions apply.</p>
.highlight-important {
background-color: yellow;
color: #333;
font-weight: bold;
}
  • class: Can be used on multiple elements. An element can have multiple classes (space-separated). Primarily used for CSS styling and grouping elements for JavaScript.
  • id: Must be unique within the entire HTML document. An element can only have one ID. Used for uniquely identifying an element, often for JavaScript manipulation or linking via fragment identifiers (#element-id).

Best Practice: Use classes for reusable styles and grouping. Use IDs for unique identifiers when necessary.