HTML class Attribute


In HTML, the class attribute is used to assign one or more class names to an HTML element. Classes are a way to apply styles and functionality to multiple elements on a page without having to repeat the same styles or scripts for each element individually. This attribute can be applied to almost any HTML element.

This is an illustration of how the class attribute is used:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Class Attribute Example</title>
  <style>
    /* CSS styling for illustration purposes */
    .highlight {
      color: red;
      font-weight: bold;
    }

    .box {
      border: 1px solid #ccc;
      padding: 10px;
      margin: 10px;
    }
  </style>
</head>
<body>

<p class="highlight">This paragraph is highlighted.</p>

<div class="box">
  <p>This is a paragraph inside a box.</p>
</div>

</body>
</html>

In this example:

  • The <p> element with the class="highlight" attribute is styled with red text color and bold font weight.
  • The <div> element with the class="box" attribute is styled with a border, padding, and margin.

Classes are not limited to styling; they can also be used with JavaScript to select and manipulate specific elements. Additionally, an element can have multiple class names separated by spaces:

<div class="box highlight">This div has both 'box' and 'highlight' classes.</div>

This allows you to combine styles or functionality from different class names.

Using the class attribute is a fundamental aspect of creating well-organized and maintainable HTML and CSS code. It facilitates the separation of concerns by keeping the structure of the HTML separate from its presentation (CSS) and behavior (JavaScript).

Post a Comment

Previous Post Next Post

Popular Items