Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

HTML class Attribute

The HTML class attribute is used to specify a class for an HTML element.

Multiple HTML elements can share the same class.


Using The class Attribute

The class attribute is often used to point to a class name in a style sheet. It can also be used by a JavaScript to access and manipulate elements with the specific class name.

The HTML class attribute example:
<html>
<head>
<style>
.mycolor {
color: red;
}
</style>
</head>
<body>
<div class="mycolor">
<h2>Patna</h2>
<p>Patna is the capital of Bihar.</p>
</div>
<div class="mycolor">
<h2>New Delhi</h2>
<p>New Delhi is the capital of India.</p>
</div>
</body>
</html>


Here are the key points about the HTML class attribute:

  • Purpose: The class attribute assigns one or more class names to an HTML element. These class names are primarily used for styling with CSS or selecting elements in JavaScript.
  • Multiple Classes: You can assign multiple class names to a single element by separating them with spaces, e.g., class="class1 class2 class3".
  • Case-Sensitive: Class names are case-sensitive (class="header" is different from class="Header").
  • CSS Usage: In CSS, you can target an element with a class by prefixing the class name with a period (.), e.g., .class1.
  • JavaScript Usage: You can use JavaScript to access and manipulate elements by their class name with methods like document.getElementsByClassName() or by using classList for managing class names dynamically.
  • Multiple Elements: The same class can be assigned to multiple elements, allowing for consistent styling or behavior across those elements.
  • No Restrictions on Name: There are no restrictions on the name, but it cannot contain spaces or start with a number in older versions of CSS.
  • Common in Frameworks: The class attribute is heavily used in CSS frameworks like Bootstrap and in JavaScript libraries such as React and Angular for structuring and applying styles.