CSS Selector Types

ADVERTISEMENT

Selectors tell the browser which HTML elements to style. They’re the foundation of every CSS rule.

🎯 Common CSS Selector Types

Selector TypeExampleSelects…
Universal*All elements
Type (Element)pAll <p> tags
Class.boxElements with class="box"
ID#headerElement with id="header"
Grouph1, h2, pAll <h1>, <h2>, and <p>
Descendantdiv pAll <p> inside <div>

🔧 Syntax and Examples

1. Universal Selector

* {
  margin: 0;
  padding: 0;
}

Resets margin and padding for all elements.

2. Type (Element) Selector

h1 {
  font-size: 2rem;
}

Targets all <h1> elements.

3. Class Selector

.card {
  background: #f9f9f9;
}

Targets all elements with class="card".

4. ID Selector

#main {
  width: 100%;
}

Targets the element with id="main".

5. Grouping Selector

h1, h2, h3 {
  font-family: 'Arial';
}

Applies the same style to multiple elements.

6. Descendant Selector

nav a {
  color: blue;
}

Targets all <a> elements inside <nav>.

🧠 Quick Tips

  • Use classes for reusable styles.
  • Use IDs sparingly (they must be unique per page).
  • Prefer grouping to reduce repetition.
  • Combine selectors for precise targeting.

ADVERTISEMENT