CSS: Rules that only match browsers without JavaScript? 🤔

"CSS" Photo by Pankaj Patel on Unsplash

You might want to add special CSS rules for browsers that don’t have JavaScript enabled, but how do you do it? I have the simple solution for you!

Why you might want this

Maybe you are using some JavaScript library that detects browser functionality, so that you can use special CSS for different browsers. But not all users use JavaScript, so you want some way to implement a fallback CSS rule that only triggers when JavaScript is disabled.

An overview of the idea

The idea is simple, we add a special class to the HTML document, and add a little script snippet that removes that class. If JavaScript is disabled, that class will never be removed. That class is then your fallback class to use when there’s no JavaScript in the browser. Genius!

How to do it

First, we add a class to the HTML tag, which you can name whatever you want. We shall use “no-js” in this example, like this:

<html class="no-js">

Then, in the HTML head, the first script you want to add before any other script is this:

<script>document.documentElement.classList.remove("no-js");</script>

Since that piece of code removes the “no-js” class, but can only be executed if JavaScript is enabled, browsers that have JavaScript disabled will retain the “no-js” class. You can now use this class to trigger rules that should only trigger without JavaScript enabled, like this:

.no-js .OnlyWithoutJavaScript {
    color: red;
}

Which gives you a CSS class named “OnlyWithoutJavaScript” that will set the text color to red, but will only trigger if JavaScript is disabled.

You can add that class to any element you like, like this:

<div class="OnlyWithoutJavaScript">
  This will render in red if JavaScript is disabled. Otherwise, it will render normally.
</div>

That’s pretty much it!

Something to note

If you just want to display a piece of text or an element, that should only appear when JavaScript is disabled, you’re better off just using the <noscript> tag, and apply your styling to that as normal. The trick I showed you above is meant to be used for fallback CSS instead. For example, if your CSS rules are generated based on a JavaScript library that detects browser support, and you want to be able to define generic rules that should work across all browsers, when detection doesn’t work because JavaScript is disabled. Of course, you should try to avoid JavaScript whenever you can, to avoid the bloat of the modern web.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.