Useful CSS Selectors
CSS Selectors that solve lots of different or unusual styling problems
- "Using CSS Mod Queries with Range Selectors", by Patrick Clancey (A List Apart)
- "Solved with CSS! Logical Styling Based on the Number of Given Elements", by Una Kravets (CSS Tricks)
- "Useful :nth-child Recipes", by Chris Coyier (CSS Tricks)
- "Level up your CSS selector skills", by David Gwyer (LogRocket)
This is a list of useful Sass/CSS code for selecting elements based on many different factors, like state and number of siblings.
General Sibling Selector
This selects all sibling elements after the indicated one by using a
~ symbol. Compare it to the direct sibling selector,
+, which only selects the sibling right next to it.
You can style elements based on if an attribute is there, regardless of any value.
There’s also several selectors that target the attribute’s values in different ways. They look for different kinds of partial matches, making them more flexible and can be fine-tuned as needed.
Select Empty Elements
If there’s nothing in an element, you can style it differently or even hide it altogether
Don’t put content in here with psuedo elements! It’s not accessible.
Select All If A Certain Amount
If you want to style items differently if there’s a certain amount (such as making them smaller if there’s at least five), use the below mixin.
Select Range of Items
Select All Items Based on Number of Siblings
mod query, as the article I’m referencing describes it, applies styles to all list elements if the list meets these two criteria:
- The number of items is devisible by the
modvalue (with or without a remainder)
- The remainder left over from the
modvalue is equal to the specified remainder
See the full mixin here:
Other selectors can also be used within this, to narrow down what items to select when this criteria is met.
There’s lots of useful child selectors that can target different ranges of elements
:nth-child()selects a specific child element
:nth-child(3)selects the third child
:nth-child(n+3)selects all children from the third onward
:nth-child(-n+3)selects only the first three children
:nth-child(3n)selects every third child
:nth-child(3n+2)selects every third child starting from the second
:nth-child(odd)selects all odd-numbered children
:nth-child(even)selects all even-numbered children
:nth-last-childselects the last element
:nth-last-child(3)is the third-to-last item
:nth-last-child(n+3)is the third to last item, and all items before it
:nth-first-childselects the first element
- Same logic as the
- Same logic as the