CSS Selectors — Full In-Depth Guide
1️⃣ Type Selector (Element Selector)
Targets all elements of a given type (tag name). For example, div will select all <div> tags.
This is a div
This is another div
div { padding: 5px; }
2️⃣ Class Selector (.)
Targets all elements that have a specific class attribute.
This div has class "blue-box"
This div has no class
.blue-box { background-color: light-blue; border: 1px solid blue; }
3️⃣ ID Selector (#)
Targets an element with a specific id attribute (must be unique on the page).
This div has id "unique-box"
Normal div
#unique-box { background-color: blue; color: white; }
4️⃣ Attribute Selector
Targets elements that have a specific attribute (and optionally a value).
This div has attribute data-type="info"
Normal div
div[data-type="info"] { border-left: 4px solid blue; }
5️⃣ Descendant Selector (Space)
Selects **all** elements inside another element, no matter how deeply nested.
.descendant-demo div { background: light-blue; }
6️⃣ Child Selector (>)
Selects **direct children only** (not deeper descendants).
Parent div
Direct child div
Nested child
Deepest div (not selected)
.child-demo > div { border: 2px solid blue; }
7️⃣ Adjacent Sibling Selector (+)
Selects the element that **immediately follows** the specified element (same parent).
First div
Second div (selected)
Third div (not selected)
.adjacent-demo div + div { background: light-blue; }
8️⃣ General Sibling Selector (~)
Selects **all siblings** after the specified element (same parent), not just the immediate one.
First div
Second div (selected)
Third div (selected)
.sibling-demo div ~ div { background: light-blue; }
9️⃣ CSS Specificity (VERY IMPORTANT)
Specificity determines **which rule wins** when multiple rules apply to the same element.
- Type selector (element) → Low specificity
- Class selector → Higher than type
- ID selector → Higher than class
- Inline styles → Highest
Example:
Div with class "blue-box" and id "unique-box"
div { color: black; }
.blue-box { color: blue; }
#unique-box { color: red; }
Result: text color will be red (ID wins)
Specificity calculation:
- Element = 0,0,0,1
- Class = 0,0,1,0
- ID = 0,1,0,0
Inline styles (like style="color: green;") have even higher specificity.
View in Details