HTML
π HTML Class and Id Attributes
1. Introduction
In HTML, every element can have different attributes.
The two most commonly used attributes are :
- class β used to group multiple elements together
- id β used to uniquely identify a single element
- π 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.
