Css Selector "(A or B) and C"?
To target elements that carry either selector A or B, both having a class named C, you can efficiently combine selectors utilizing comma for OR logic and concatenate for AND logic:
Looking for an example? Queue the <div>
or <p>
having a .highlight
class:
In this case, A.c grapples with A having C and B.c goes for B having C, with both selectors bonded by the comma indicating OR logic.
Leveling Up: Using the :is()
Pseudo-class
While the standard approach works well, there's a niftier way to achieve the same using the :is()
pseudo-class. This provides a more condensed and neat syntax. The catch? It's an experimental CSS feature. Big words, I know.
This :is()
function selects any elements having the .c
class that are also A or B. But, always check for browser support before incorporating :is()
extensively.
The CSS Preprocessor Charm: LESS or SASS
Believe it or not, there's no better method to group multiple logical combinations efficiently in CSS than the humble comma operator. However, preprocessors like LESS or SASS can add a magic touch. They empower you with features to write complex logical styling in a more structured way.
Consider the :not()
pseudo-class for excluding certain elements from the selection. E.g., .x:not(.c)
.
Remember: preprocessors compile down to standard CSS, and are not native CSS jargon.
Gauge Selector Specificity & Embrace Practicality
Selector specificity isn't just a fancy term. It's crucial. Different selectors have different weights affecting the cascade and eventually the final styling.
Weigh the specificity and usability when deciding your combat force between :is()
, :not()
, and our old friend, the comma operator.
Browser Support & Preprocessors: Best Pals or Worst Enemies?
Newer CSS features like :is()
might sound like the next big thing, but browser compatibility can be a spoiler. Reminder: CSS preprocessors require to be compiled into CSS and not all workflows support them.
Structured for Precise Selection
A trick for complex logical combinations: consider using sub-classes, like .a.x, .b.x
. It improves target selection with an added bonus of enhanced performance and readability.
Future Proofing: Keep an Eye on :is()
Finally, with the :is()
function being experimental, it's wise to keep watching CSS Working Group (CSSWG) drafts to know when it moves from experimental to standard.
Was this article helpful?