Explain Codes LogoExplain Codes Logo

How to exclude particular class name in CSS selector?

html
css
specificity
selectors
Nikita BarsukovbyNikita Barsukov·Aug 6, 2024
TLDR

The bread and butter of excluding particular class names in your CSS selectors is the :not() pseudo-class. This precious stone allows you to apply styling rules to elements that do not have a specific class. Here's the magic spell:

.item:not(.skip) { /* Magic shall happen here */ }

It will breathe fire at the .item classes, thou shall not pass if you bear the .skip class on top.

Selector precision and override - order of the Phoenix

Stay vigilant when wielding compound selectors, such as combining pseudo-classes with class selectors. Order and specificity are the keys to unlock the full potential of your styles. One does not simply place a pseudo-class at a wrong position:

/*.reMode_hover:not(.reMode_selected):hover This is the way */ .reMode_hover:not(.reMode_selected):hover { /*Forsooth! The hover effect sees not the 'reMode_selected' class, it's invisible like Sauron's ring */ background-color: #f0ac00; }

To triumph over conflicts with previous rules, thou might need to call upon a more specific selector:

/* Swipe right on 'reMode_hover:hover' only if 'reMode_selected' is a match */ a.reMode_selected.reMode_hover:hover { /* Perform the style charm here */ }

Trust not the idiot's guide to CSS, one must test in combat using **JSFiddle or die in horror as your styles disobey you.

No JS - the sorcerer's stone

Fall not for the alluring illusion of JavaScript for conditional styles. Combine the arcane power of :not() with CSS3, cast wand-less spells, maintain performance, and cleaner scrolls.

A CSS potterhead

Master the CSS spells like :not() and craft cleaner and efficient scrolls. Here's the map to the Chamber of Secrets:

Specificity and the cascade - the order of spells

Master CSS specificity — with great power comes great specificity. Get the upper hand when dueling with :not():

/* Specificity hierarchy - It's LeviOsa, not LevioSA. */ #id > .class > tag

Browser compatibility - the goblet of fire

Before launching, check the Triwizard tournament champions on Can I Use. Beware, He-who-must-not-be-named has cursed selectors' lists while casting the :not() spell.

Testing and validation - the quidditch cup

Validate your scrolls by testing in the Great Hall without Dementors around. Getting community upvotes is as good as catching the golden snitch.