Styling HTML with CSS when JavaScript is not available

| No Comments

It’s a pretty good chance that most browsers today have JavaScript enabled. However in the odd case that someone views a site that relies heavily on JavaScript it’s good to at least provide a page that doesn’t look broken.

Using jQuery for a lot of projects I’ve been using a very simple solution. Pages are published with the class no-js on the <body> tag. Then when the jQuery loads, the first function removes this class.

To style for situations when jQuery is not available, add no-js as the first selector.

Here’s an example:

<html>
    <head>
        <style type="text/css">
            .foo {
                /* default styles */
                background-color: blue;
            }
            .no-js .foo {
                /* style when js not available */
                background-color: red;
            }
        </style>
    </head>
    <body class="no-js">
        <div class="foo">
            <p>I'm foo!</p>
            <p>If my background is <strong>blue</strong>, then javascript is active... 
            if <strong>red</strong>, then javascript is not active.</p>
        </div>
        <script type="text/javascript">
            $(function() {
                $('body').removeClass('no-js');
            });
        </script>
    </body>
</html>

Leave a comment