P2.1: CSS Selectors & Specificity

To style HTML elements, CSS needs to target them. Selectors define exactly which HTML elements receive specific style declarations.


1. CSS Selector Hierarchy

CSS supports several selectors of varying targeting strengths:

  • Element Selector: Targets HTML tag names directly (e.g. h1, p).
  • Class Selector (.): Targets elements with a class attribute (e.g. .btn, .card).
  • ID Selector (#): Targets a single element with a unique ID attribute (e.g. #header).
  • Group Selectors: Combines multiple selectors separated by commas (e.g. h1, h2, p).

CSS Specificity Weight Scale

Higher specificity scores override lower ones regardless of sheet order.

Wes Bos

Wes BosView Profile 🔗

Real-World Developer Case Study
11 Years Exp
RoleFull Stack CSS/JS Educator
Salary₹55 Lakhs/yr equivalent
CompanySyntax.fm
Core Tech Stack
CSS SelectorsFlexboxJavaScript ES6Node.js

If you don't understand CSS specificity, you'll spend hours fighting your own stylesheets by adding !important tags. Learn how selector weight calculations work!


2. Resolving Specificity Conflicts

When two rules target the same element:

  1. Specificity Score: The selector with the higher specificity score wins.
  2. Order of Appearance: If scores are equal, the rule declared last (lower down the sheet) wins.

🎓 Practice Assignment

  1. Create a page selector.html containing an <h1> tag with class title and ID main-title.
  2. Style the tag using an element selector (red), class selector (green), and ID selector (blue) in the same stylesheet.
  3. Open it in Chrome to verify that the ID style (blue) wins due to specificity.
Advertisement
NS
Ask Nextsem
AI Mode
NS
Home
Course
Playground