Blog

Understanding CSS Selectors & Specificity for Scalable UI Design

Written by Mukesh Saini | 26 Dec, 2025 11:30:00 AM

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:

  1. Inline styles (style="") Highest
  2. IDs (#id)
  3. Classes, attributes, pseudo-classes (.class, [attr], :hover)
  4. 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

  1. Diagram showing type, class, ID hierarchy
  2. GIF highlighting multiple selectors and which one takes effect
  3. Screenshot of DevTools showing applied styles and specificity