πŸ“Œ HTML Class and Id Attributes

1. Introduction

In HTML, every element can have different attributes.

  1. The two most commonly used attributes are :

  2. class β†’ used to group multiple elements together
  3. id β†’ used to uniquely identify a single element
  4. πŸ‘‰ These two attributes are generally used for styling with CSS.

2. What is class ?

  • class allows the same style to be applied to multiple HTML elements
  • The same class name can be used multiple times on a page
  • It is ideal for grouping elements

🧱 Example

HTML

<style>
    .city {
        background-color: lightblue;
        color: white;
        padding: 15px;
        margin: 10px 0;
    }
</style>
    <div class="city">London</div>
    <div class="city">Paris</div>
    <div class="city">Tokyo</div>
                

🟒 Explanation:

These three <div> elements have the same appearance because they share the city class.

πŸ”Ή 3. What is id ?

  • id is used to make an element unique within a page
  • The same id value should only be used once
  • In CSS, it is selected using the # symbol

🧱 Example

HTML

<style>
    #special {
        background-color: orange;
        color: white;
        padding: 15px;
    }
</style>
<div id="special">This is a unique section</div>
                

🟒 Explanation:

This style is applied only to the element with id="special"

This allows it to belong to a group while also receiving special styling.

🧱 Example

HTML

<style>
    .box{
        background-color: lightgray;
        padding: 10px;
        border: 1px solid black;
    }
    #highlight{
        background-color: yellow;
        border-color: red;
    }
</style>
<div class="box">Normal Box</div>
<div class="box" id="highlight">Special Box</div>
                

🟒 Explanation:

  • Both <div> elements get the .box
  • The second <div> also gets extra styling from its id
  • Since id has higher priority, its styles override the class where applicable

πŸ”Ή 5. Using Multiple Classes

You can assign multiple classes to a single element.

This allows you to combine different styles.

🧱 Example

HTML

<style>
    .card { padding: 15px; border: 1px solid gray; }
    .shadow { box-shadow: 2px 2px 5px gray; }
    .rounded { border-radius: 10px; }
</style>
<div class="card shadow rounded">
    This card has multiple classes!
</div>
                

🟒 Explanation:

This element uses 3 classes at the same time and combines all their styles.

  • 🎯 Quick Note

  • class β†’ used to style and organize multiple elements
  • id β†’ used to target a single element (e.g., for JavaScript or special styling)
  • πŸ‘‰ Additionally, id can also be used to create links to specific sections within a page.