CSS Exceptions – The :not pseudo-class explained

This blog contains clear instructions on using the ‘:not pseudo-class’ to hide items from logged out users and make exceptions to custom CSS.

Yesterday I was asked by a Page Builder Everywhere customer if it was possible to only show the added sections that the plugin creates on certain pages. The answer is yes, using the :not pseudo-class. But actually, there’s a whole bunch of reasons that the :not pseudo-class is pretty cool and I want to share some of them with you…

If you’re fairly familiar with CSS then you’ll have no doubt come across ways of limiting your changes. For example, media queries are widely use to control the way your website looks on different devices or screen orientations. I’ve blogged before about using page IDs to change single page styles and there’s a whole section in the Divi Selectors eBook on the body classes that are added to Divi & WordPress, as well as how they can be used to make section specific changes. But what if you want to change the CSS everywhere EXCEPT one page? This is where the :not pseudo-class comes in handy.

not: pseudo-classes explained

If you wanted to change the colour of all the h1 titles on your website then you could just use CSS like this:

h1 { color: red; }

But if you wanted to change all of the h1 titles EXCEPT those on the home page then you could take advantage of the ‘.home’ class that WordPress adds to the page set as the domain’s landing page. Like this:

body:not(.home) h1 { color: red; }

Here, you’re basically saying “apply this change, but NOT if the .home class is present”. This is the cleanest way of creating exceptions to your CSS rules.

 

Browser Support

browser support

Image from W3 schools

The :not pseudo-class has great browser support and has for a while. You shouldn’t need browser prefixes.

 

Two Practical Uses

Here is two examples of how to use the :not pseudo-class to your advantage.

Page Builder Everywhere (Home page only)

In the case of the Page Builder Everywhere plugin and limiting its visibility to just the home page: all you need to do is add ‘home-only’ as a class to your custom sections and then paste this code into your style sheet or ePanel…

body:not(.home) .home-only { display: none }

 

Hide Sections From Logged Out Users

not member

If you want to hide sections from logged out users then add ‘not-member’ as a class to the section you want to hide, and then paste the following code into your style sheet…

body:not(.logged-in) .not-member { display: none }

 

We hope you have fun experimenting with CSS exceptions! Let us know in the comments how you use it.

 

Stephen James

SJ is a web developer living in the coastal town of Southsea, England. He is a Divi and WordPress advocate and the founder of Divi Space.