2 Minutes Read
Listen to the Blog
Understanding CSS Selectors & Specificity for Scalable UI Design
1:12
Target HTML elements precisely and understand which styles take priority using CSS selectors and specificity.
What Are CSS Selectors?
Selectors define which HTML elements a CSS rule applies to.
p { color: blue; }
This applies to all <p> elements
Common Selector Types
1. Type Selector
Targets elements by tag name:
h1 { font-size: 24px; }
2. Class Selector .
Targets elements with a specific class using
.highlight { background-color: yellow; }
This is highlighted text.
3. ID Selector
Targets a single element with #
#main-header { text-align: center; }
Welcome
Attribute Selector
Targets elements with specific attributes
input[type="text"] { border: 1px solid gray; }
Combinators
1. Descendant Selector
div p { color: green; }
Applies to <p> inside a <div>
2. Child Selector
div > p { font-weight: bold; }
Applies only to direct children
3. Adjacent Sibling Selector
h2 + p { margin-top: 0; }
Targets the <p> immediately after <h2>
CSS Specificity
Determines which CSS rule wins when multiple rules target the same element
Specificity hierarchy:
- Inline styles (style="") Highest
- IDs (#id)
- Classes, attributes, pseudo-classes (.class, [attr], :hover)
- Type selectors (div, p) Lowest
Example:
p { color: blue; /* Type selector */ } .highlight { color: green; /* Class selector */ } #special { color: red; /* ID selector */ }
Specificity example
Result: Text will be red because ID has higher specificity
Visual Suggestions
- Diagram showing type, class, ID hierarchy
- GIF highlighting multiple selectors and which one takes effect
- Screenshot of DevTools showing applied styles and specificity