Difference between class and ID attribute of CSS ?
In : BSc IT Subject : Web DesigningIn HTML and CSS, both class and id are used to apply styles or manipulate elements with JavaScript, but they serve different purposes.
The class attribute is used when you want to apply the same style or behavior to multiple elements on a webpage. It allows you to group elements under a common name and apply shared styles using a class selector (e.g., .my-class).
On the other hand, the id attribute is used to uniquely identify a single element on the page. Each id must be unique within the document, making it ideal for targeting specific elements for styling or scripting.
In CSS, id selectors (e.g., #my-id) have higher priority than class selectors, meaning styles applied via an ID can override those applied via a class.
Additionally, ids are often used for anchor links and JavaScript DOM manipulation because they provide a direct reference to a unique element. While an HTML element can have multiple classes, it can only have one id, and while classes are great for reusable styles, IDs are best reserved for unique elements like main content sections, headers, or footers.
Example :
<style>
.box {
padding: 20px;
}
.shadow {
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
#main-content {
background-color: #f9f9f9;
}
</style>
<body>
<div id="main-content" class="box shadow">
This is a special box with unique ID and shared classes.
</div>
</body>