Element, Class, and ID Selectors
Element, Class, and ID Selectors
Select an element by tag name, an optional reusable class, or a unique identifier.
What you’ll learn
- Use element, class and ID selectors.
- Explain why a class can style multiple elements.
- Choose reusable classes for components.
Understand the concept
An element selector such as p targets matching tags. A class selector such as .featured targets any element carrying that class. An ID selector such as #summary targets an element by its ID.
Classes are usually the most practical styling hook for reusable components. An ID should be unique in a document and is often better reserved for references or behavior.
Visualize the relationship
Target every paragraph
The tag selector applies to both paragraphs.
HTML
<p>Monday report</p><p>Tuesday report</p>CSS
p { color: #0f766e; padding: 6px; }Rendered output
Monday report
Tuesday report
Observe: Both paragraphs receive the same text color and padding.
Use classes and IDs
Style reusable alerts and one particular summary.
HTML
<p class="featured">Important message</p><p class="featured">Another important message</p><p id="summary">Final summary</p>CSS
.featured { background: #fef3c7; padding: 8px; }
#summary { border-left: 4px solid #2563eb; padding-left: 12px; color: #1d4ed8; }Rendered output
Important message
Another important message
Final summary
Observe: The class rule affects two paragraphs, while the ID rule affects only the summary.
Explain the result
<code>p</code> selects paragraphs, <code>.featured</code> selects class="featured", and <code>#summary</code> selects id="summary".
Compare the two examples: identify the selector, each changed property, and which visible part of the output proves that the CSS took effect.
Common mistakes to avoid
- Use
.before a class selector and#before an ID selector. - Avoid reusing the same ID for multiple unrelated elements.
Try it yourself
Add class="featured" to a third paragraph; observe whether you need another CSS declaration.
Before changing the code, predict what will change. Then verify by checking the rendered result.
Check your understanding
What you should remember
Tags select by HTML element name; classes are reusable; IDs identify a particular element.
Revisit the rendered examples if the rule still feels abstract. Change one declaration at a time so you can connect cause and effect.
Reaching the recap and completing the quizzes are separate milestones.