HTML Class

HTML class:

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

·        
Group
elements together for styling and targeting.

 

In the following example we have two <div> elements with a class
attribute with the value of “Country”. The two <div> elements
will be styled equally according to the country style definition in the head
section:

 

 

 

<!DOCTYPE
html>

<html>

<head>

<style>

.country
{

  background-color:
blue;

  color:
white;

  border:
2px solid
black;

  margin:
20px;

  padding:
20px;

}

</style>

</head>

<body>

 

<div
class=“country”>

  <h3>India</h3>

  <p>My
favorite country
</p>

</div>

 

<div
class=“country”>

  <h3>Switzrland</h3>

  <p>Best
visting place
</p>

</div>

 

</body>

</html>

 

 

 

Output:

 

 

HTML Class and ID:

 

Class:

Purpose: Used to group elements that share common styles or behaviors.

Syntax: <element class=”className”>Content</element>

Reusability: A class can be applied to multiple elements on a page.

Selector: In CSS, use a period (.) to target elements with a specific class: .className { /* styles here */ }

ID:

Purpose: Assigns a unique identifier to an element for specific styling or manipulation.

Syntax: <element id=”uniqueID”>Content</element>

Uniqueness: An ID can only be used once per page.

Selector: In CSS, use a hash symbol (#) to target the element with the ID: #uniqueID { /* styles here */ }

 

Feature

                              Class

                       ID

Reusability

Can be used multiple times

               Can only be used once

Specificity

Lower specificity in CSS

         Higher specificity in CSS

Targeting

Used for general styling and behavior

 Used for targeting unique elements for    Styling or JavaScipt

 

 

Examples:

Class:

  <p class=“error”>Please correct the errors in the form.</p>

<p class=“error”>This field is required.</p>

 

<style>

.error {

  color: red;

  font-weight: bold;

}

</style>

 

 

ID:

Example:

<div id=“main-content”>

    <h1>Welcome to my website!</h1>

    <p>This is the main content area.</p>

  </div>

 

  <script>

  document.getElementById(“main-content”).style.backgroundColor = “lightblue”;

 

  </script>

Join Our Newsletter