LearningCSS TutorialSelectors & Specificity
CHAPTER 03 · BEGINNER

CSS Selectors & Specificity

CSS selector decide karta hai ki style kis HTML element par apply hoga. Jab multiple rules same element ko target karte hain, cascade aur specificity decide karte hain kaunsa rule win karega.

English + Hinglish22 min readPractice included

What is a CSS selector?

A selector is the part of a CSS rule that chooses one or more HTML elements.

selector.cssCSS
p {
  color: #334155;
}

Here p selects every paragraph element on the page.

Hinglish Explanation

Selector ko address samjho. Browser selector ko dekhkar find karta hai ki CSS rule kis element ya elements par lagana hai.

Element selector

An element selector targets all elements with the same HTML tag name.

element-selector.cssCSS
h2 {
  color: #0b7cff;
}

p {
  line-height: 1.7;
}
Use case: Jab same type ke saare elements ko common base style dena ho, element selector useful hota hai.

Class selector

A class selector starts with a dot .. Classes are reusable and can be applied to many elements.

HTML + CSSEXAMPLE
<p class="highlight">Important note</p>
<div class="highlight">Highlighted box</div>

.highlight {
  background-color: #eaf3ff;
  color: #0b3a73;
}
Hinglish Explanation

Class reusable hoti hai. Agar multiple elements ko same styling deni ho to class generally best choice hoti hai.

ID selector

An ID selector starts with # and targets an element with a matching id.

ID exampleCSS
<section id="hero">...</section>

#hero {
  padding: 40px;
}
Practical advice: IDs HTML me navigation, labels aur scripting ke liye useful hain. Reusable styling ke liye classes ko prefer karna CSS ko easier to maintain rakhta hai.

Universal and grouping selectors

The universal selector * can target every element. A comma groups selectors so they share declarations.

grouping.cssCSS
* {
  box-sizing: border-box;
}

h1,
h2,
h3 {
  color: #0b1f3a;
}

Grouping avoids repeating the same declarations for multiple selectors.

Descendant and child combinators

Combinators describe relationships between elements.

relationships.cssCSS
/* Any paragraph inside article */
article p {
  color: #475569;
}

/* Only direct li children of .menu */
.menu > li {
  padding: 8px 12px;
}
Difference

article p article ke andar kisi bhi depth par paragraph select karta hai. .menu > li sirf direct child li ko select karta hai.

Sibling combinators

The adjacent sibling selector + targets the next sibling. The general sibling selector ~ targets following siblings that match.

siblings.cssCSS
h2 + p {
  font-weight: 600;
}

h2 ~ p {
  color: #475569;
}

h2 + p only styles the first matching paragraph immediately after an h2.

Attribute selectors

Attribute selectors target elements based on attributes or attribute values.

attributes.cssCSS
input[required] {
  border-color: #f59e0b;
}

input[type="email"] {
  background-color: #f8fafc;
}
Use case: Forms me input type ya state ke basis par styling karne ke liye attribute selectors kaafi useful hote hain.

Pseudo-classes

Pseudo-classes select an element in a particular state. They start with a colon.

pseudo-classes.cssCSS
a:hover {
  text-decoration: underline;
}

button:focus {
  outline: 3px solid #93c5fd;
}

li:first-child {
  font-weight: 700;
}
Accessibility: Hover style ke saath keyboard focus state ko bhi visually clear rakho. Sirf mouse users ke liye interaction design mat karo.

Pseudo-elements

Pseudo-elements target a specific part of an element and commonly use double colons.

pseudo-elements.cssCSS
p::first-letter {
  font-size: 2rem;
}

.note::before {
  content: "Note: ";
  font-weight: 700;
}

Generated content should not be the only place where important meaning is communicated.

What is specificity?

Specificity is one part of the cascade. When competing declarations have the same origin, importance and cascade layer, the selector with higher specificity can win.

specificity.cssCSS
p {
  color: blue;
}

.message {
  color: green;
}

#notice {
  color: red;
}

For an element like <p id="notice" class="message">, the ID selector has higher specificity than the class and element selectors, so its normal declaration wins in this simple example.

Beginner hierarchy

Simple normal-author rules me roughly yaad rakho: ID > class/attribute/pseudo-class > element/pseudo-element. Lekin specificity poori cascade nahi hai—importance, origin aur cascade layers pehle matter kar sakte hain.

A simple specificity score model

For learning, think in three columns: IDs, class-like selectors, and element-like selectors.

specificity examplesGUIDE
p                  → 0-0-1
.card              → 0-1-0
#hero              → 1-0-0
.card p            → 0-1-1
#hero .card p      → 1-1-1
input[required]    → 0-1-1
button:hover       → 0-1-1

Compare from left to right. More IDs wins first; if tied, compare the class-like column; if still tied, compare element-like selectors.

Do not treat this as normal arithmetic. 0-10-0 does not become 1-0-0. Columns are compared separately.

What if specificity is equal?

If competing declarations are otherwise equal and have the same specificity, the later declaration wins.

source-order.cssCSS
.card {
  color: blue;
}

.card {
  color: red;
}

The second rule appears later, so the text becomes red.

Inline styles and !important

Inline style declarations generally outrank normal stylesheet selectors within the same author origin. !important changes the importance level and should not be used as a shortcut for poorly structured CSS.

avoid-overuse.cssCSS
/* Avoid using !important everywhere */
.alert {
  color: red !important;
}
Better approach

Agar har dusre rule me !important lagana pad raha hai, selectors aur CSS structure review karo. Specificity ko unnecessarily high mat banao.

Specificity vs inheritance

Some CSS properties, such as color, can inherit from a parent. A declaration that directly targets an element normally beats a value that element only inherited.

inheritance.cssCSS
body {
  color: #334155;
}

p {
  color: #0b7cff;
}

Paragraphs get blue because they are directly styled, instead of only inheriting the body color.

Selector best practices

  • Reusable component styling ke liye classes prefer karo.
  • Selectors ko unnecessarily long aur deeply nested mat banao.
  • IDs ko reusable styling ka default mat banao.
  • !important ko routine fix ke tarah use mat karo.
  • Hover ke saath focus states bhi design karo.
  • Selector ko HTML structure se itna tightly couple mat karo ki small markup change se CSS break ho jaye.

Common beginner mistakes

  • Class selector me dot . bhoolna.
  • ID selector me hash # bhoolna.
  • Descendant aur direct-child selector ko same samajhna.
  • Specificity ko sirf “last rule always wins” samajhna.
  • Har conflict ko !important se solve karna.
  • Very long selectors banana jo maintain karna difficult ho.

Practice Task

“Student Cards” naam ka small HTML section banao aur selectors practice karo.

  1. All paragraphs ko element selector se base color do.
  2. Three cards ko same .student-card class do aur common styling apply karo.
  3. Ek featured card ko extra class dekar different background do.
  4. Required email input ko attribute selector se style karo.
  5. Button ke liye :hover aur :focus states banao.
  6. .student-card p aur .student-card > p ka difference test karo.
  7. Ek specificity conflict banao using element, class aur ID selectors; browser result predict karke verify karo.
  8. Last me ID styling ko class-based solution me refactor karne ki koshish karo.