5 min read
ā¢Question 8 of 49easyWhat is the difference between id and class?
Two ways to identify elements.
What You'll Learn
- Key differences between id and class
- CSS specificity implications
- Best practices for using each
The Key Difference: Uniqueness
id- Must be unique on a page (only one element can have it)class- Can be reused (multiple elements can share it)
CSS Specificity
id has higher specificity (100) than class (10), so id styles override class styles.
index.htmlHTML
<style>
#special { color: red; } /* specificity: 100 */
.highlight { color: blue; } /* specificity: 10 */
</style>
<!-- This text will be RED because id wins -->
<p id="special" class="highlight">Hello</p>HTML Examples
index.htmlHTML
<!-- id: unique identifier -->
<header id="main-header">Only one main header</header>
<form id="contact-form">...</form>
<!-- class: reusable styling -->
<p class="highlight">Styled paragraph</p>
<p class="highlight">Same styling here</p>
<p class="highlight warning">Multiple classes</p>JavaScript Targeting
code.jsJavaScript
document.getElementById('main-header'); // one element
document.getElementsByClassName('highlight'); // collection
document.querySelector('#main-header'); // one element
document.querySelectorAll('.highlight'); // NodeListBest Practice
- Use
classfor styling (more flexible, reusable) - Reserve
idfor unique elements that JavaScript needs to target