The difference between id
and class
in HTML primarily lies in their usage and how they are targeted by CSS and JavaScript.
Differences Between id
and class
Uniqueness:
id
: Anid
must be unique within a document. Only one element can have a particularid
.class
: Aclass
can be reused on multiple elements. Many elements can share the same class.
Usage:
id
: Typically used to identify a single element for styling or JavaScript manipulation.class
: Used to apply the same styles to multiple elements or to group elements for JavaScript manipulation.
CSS Selectors:
id
: Targeted with#
in CSS.class
: Targeted with.
in CSS.
Specificity:
id
: Has a higher specificity in CSS compared to a class, meaning styles applied with anid
selector will override those applied with a class selector if both are applied to the same element.
Using id
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HTML id Example</title> <style> #unique-element { color: red; font-size: 24px; } </style> </head> <body> <div id="unique-element">This element has a unique id.</div> </body> </html>
Using class
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HTML class Example</title> <style> .shared-class { color: blue; font-size: 20px; } </style> </head> <body> <div class="shared-class">This div shares the class.</div> <p class="shared-class">This paragraph also shares the same class.</p> </body> </html>
Combined Example
In this example, both id
and class
are used on different elements:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HTML id vs class Example</title> <style> #unique-element { color: red; font-size: 24px; } .shared-class { color: blue; font-size: 20px; } </style> </head> <body> <div id="unique-element" class="shared-class">This element has both an id and a class.</div> <p class="shared-class">This paragraph shares the class.</p> </body> </html>
Key Points
- Use
id
when you need a single, unique identifier for an element. - Use
class
when you want to apply the same styles or behaviors to multiple elements. - Remember that
id
has a higher specificity in CSS, so it can override class styles if both are applied to the same element.