๐ŸŽจ CSS Fundamentals

CSS Selectors Cheatsheet: Every Selector You'll Actually Use

By The CodeCraft Teamยทยท8 min read
CSS selector syntax printed on a colorful gradient background

Selectors are how CSS finds the elements you want to style. The better you know them, the less BEM-style class soup you have to write. Here's the practical list โ€” no obscure edge cases, just what real production code uses.

Basic selectors

  • * โ€” universal
  • tag โ€” element type
  • .class โ€” class
  • #id โ€” id (avoid for styling)
  • [attr=value] โ€” attribute

Combinators

  • A B โ€” descendant
  • A > B โ€” direct child
  • A + B โ€” adjacent sibling
  • A ~ B โ€” general sibling

Powerful pseudo-classes

/* every other row */
tr:nth-child(even) { background: #f7f7f7; }

/* style a card when it contains an image */
.card:has(img) { padding-top: 0; }

/* style inputs only after the user has interacted */
input:user-invalid { border-color: red; }

:has() โ€” the parent selector we waited 20 years for

Available in every modern browser since 2023, :has() lets you style an element based on its descendants. Use it for conditional layouts without JavaScript.

Specificity in one sentence

Inline > id > class/attr/pseudo-class > tag/pseudo-element. When in doubt, use a slightly more specific selector โ€” never !important.

Frequently asked questions

Is :has() safe to use in production?

Yes โ€” it's supported in Chrome, Edge, Safari, and Firefox since 2023.

Should I use id selectors?

Rarely. They have very high specificity and make CSS hard to override. Prefer classes.

External references

Enjoyed this article?

Share it with a fellow developer or explore more tutorials in our blog.

More articles

Related articles