1. Basic Selectors

Basic selectors target elements by tag, class, or ID.


p { color: #333; } /* Type */
.highlight { background: yellow; } /* Class */
#header { padding: 1rem; } /* ID */
  

2. Grouping & Universal


h1, h2, h3 { font-family: 'Segoe UI', sans-serif; }
* { box-sizing: border-box; }
  

4. Attribute Selectors


input[type="text"] { width: 200px; }
a[href^="https"] { color: green; }
a[href$=".pdf"]::after { content: "📄"; }
img[alt*="logo"] { border: 1px solid #ccc; }
  

5. Pseudo-classes


a:hover { text-decoration: underline; }
input:focus { outline: 2px solid royalblue; }
li:first-child { font-weight: bold; }
li:nth-child(odd) { background: #f8f8f8; }
  

6. Pseudo-elements


p::first-line { font-weight: bold; }
p::before { content: "💡 "; color: orange; }
  

7. Advanced Selectors

:not(), :is(), :where(), :has() allow complex matching:


button:not(.primary) { opacity: 0.7; }
:is(h1, h2, h3) { margin-block: 0.5em; }
article:has(img) { border: 1px solid #ddd; }
  

Best Practices

  • Keep specificity low by favoring classes over IDs.
  • Combine selectors carefully to avoid brittle CSS.
  • Test across browsers for newer selectors like :has().

Conclusion

Mastering CSS selectors lets you write scalable, maintainable CSS for clean and consistent UI design.