Oliver Wolfson
ServicesProjectsContact

Development Services

SaaS apps · AI systems · MVP builds · Technical consulting

Services·Blog
© 2026 O. Wolf. All rights reserved.
Web DevelopmentProgramming
Mastering CSS Selectors: A Practical Guide
CSS selectors are the foundation of styling web pages. They allow you to target HTML elements precisely so you can apply custom visual styles. In this guide, we'll explore the core types of selectors and how they work—with an interactive React demo to reinforce your learning.
June 19, 2025•O. Wolfson

CSS selectors are the foundation of styling web pages. They allow you to target HTML elements precisely so you can apply custom visual styles. In this guide, we'll explore the core types of selectors and how they work—with an interactive React demo to reinforce your learning.

Component "CssSelectorsDemo" is not available. Please define it in the MDX components.

🏷️ 1. Element Selector

Example: div, p, h1 Targets HTML tags directly.

div {
  background-color: lightblue;
}

🔹 Use this when you want to apply styles to all instances of a tag.


🧩 2. Class Selector

Example: .card, .highlight

.card {
  border: 1px solid #ccc;
  padding: 1rem;
}

🔹 Great for reusing styles across multiple elements.


🆔 3. ID Selector

Example: #header, #main-title

#header {
  font-size: 2rem;
  color: navy;
}

⚠️ IDs should be unique within a page. Use this for one-off elements.


🔍 4. Attribute Selector

Example: input[type="text"]

input[type="text"] {
  border: 2px solid green;
}

🔹 Perfect for styling based on element attributes—forms, links, etc.


🔍 5. Pseudo-class Selector

:hover, :nth-child(n), :focus

div:hover {
  background-color: #def;
}

li:nth-child(3) {
  font-weight: bold;
}

🔹 These respond to user interaction or element position.


🌟 6. Pseudo-element Selector

::before, ::after

.card::before {
  content: "👉";
  margin-right: 0.5rem;
}

🔹 Use these to insert content or style parts of an element.


Specificity: What Happens When Selectors Conflict?

When multiple rules apply, specificity determines which style wins:

Selector TypeSpecificity Score
Element (div)0,0,0,1
Class (.card)0,0,1,0
ID (#header)0,1,0,0

Higher scores win. Inline styles and !important can override even ID rules—but use them sparingly.


🧪 Try It Live

Use the React component (included in this demo) to interact with various selectors. Select a rule, and the matching element will highlight. Try hovering, changing inputs, and inspecting the result to build intuition.


Conclusion

Understanding how CSS selectors work—and how to apply them efficiently—makes your stylesheets cleaner, more reusable, and easier to maintain. Practice combining selectors, and don't forget to consider specificity in your decisions.

Tags
#css#css 3#style#styles