Build A Simple Style Switcher in CSS

    Laurence Veale
    Laurence Veale
    Share

    If, like many SitePoint readers, your Website relies on CSS, this article is for you. In it, I’ll show you a simple technique that will allow your visitors to choose the way they see your site.

    As well as adding a powerful ‘WOW!’ factor, this technique can also provide great accessibility benefits to your site. While I’ll use PHP to illustrate this technique, the concepts are simple enough to be applied to other languages such as ASP, Java or even client-side JavaScript.

    One Stylesheet to Rule them All

    Generally, we have one main stylesheet that controls the look and feel of our (X)HTML.

    <link rel="stylesheet" type="text/css" href="/style/default.css" media="screen" />

    Within this stylesheet, we commonly set rules for the appearance and, perhaps, layout of headings, paragraphs, navigation menus and other elements in the page.

    We may even have gone so far as to use a separate stylesheet for printing:

    <link rel="stylesheet" type="text/css" media="print" href="style/print.css" />
    Colours of the Rainbow

    Why not give your visitors a choice of styles? Of course, there is already a well-established method by which we can supply alternate stylesheets:

    <link rel="alternate stylesheet" type="text/css" media="screen" href="style/green.css" title="green"/> 

    <link rel="alternate stylesheet" type="text/css" media="screen" href="style/white.css" title="white"/>

    <link rel="alternate stylesheet" type="text/css" media="screen" href="style/orange.css" title="orange" />

    However, there are a few known drawbacks to this technique:

    • Many modern browsers (including Internet Explorer) are unable to access the alternate stylesheets.
    • Style selection is stateless: the visitor’s choice is not remembered from one visit to the next, nor from page to page.

    An Alternative Approach

    The alternative solution involves three steps:

    1. The users select their preferred style — they click a hyperlink or choose an option from a dropdown list.

    2. The server-side script reads the visitors’ selection and sets a cookie on their machine to record that selection.

    3. On every subsequent visit, this cookie is recalled by our server-side script and the perferred stylesheet is selected accordingly.

    Let’s look at each of these steps in detail.

    1. Choose the Preferred Style

      1420_stylechoice

      We use the following links to reflect each stylesheet option.

      • <a href="https://www.sitepoint.com/stylechanger.php?style=green"><img src="greensq.gif" alt="green"/></a>
      • <a href="https://www.sitepoint.com/stylechanger.php?style=white"> "><img src="whitesq.gif" alt="white"/></a>
      • <a href="https://www.sitepoint.com/stylechanger.php?style=orange"> "><img src="orangesq.gif" alt="orange"/></a>
    2. Yummy, Cookies!

      The stylechanger.php file contains the following code:

      <?php 
      $theStyle    = $HTTP_GET_VARS["style"]; /* querystring */
      setcookie("style", $theStyle, time()+36000, "/", "");
      header("Location: $HTTP_REFERER");
      exit;
      ?>

      All the above code does is get the selected style that was passed in the querystring (style=green/white/orange) and write that choice to a cookie on the visitor’s PC. Easy!

    3. Trend-Setting

      From now on, we’ll need to add the following code to any page on which we want to implement the visitor’s style selection:

      <?php 
      $styleCookie = $HTTP_COOKIE_VARS["style"];

      switch($styleCookie)
       {

        case "white":
        case "orange":        
             break;
        case "green":
        case "":
             $styleCookie = "default";
             break;      
       }
       
       $styleSheet  = "<link rel="stylesheet" type="text/css" href="/style/$styleCookie.css" media="screen" />n";

      echo $styleSheet;
      ?>

      This section of code reads the cookie stored in the user’s browser. If it’s either ‘white’ or ‘orange’, we’ll hardcode that stylesheet into the header. On the other hand, if the cookie is blank (i.e. no cookie is present) or green, we’ll use our default stylesheet — in this case, the green one.

      The default green stylesheet renders the page like so:

      1420_green

      And that’s it… almost!

    Our 'default.css' stylesheet contains the default set of rules that describe the appearance of our page, while our alternate stylesheets, as the name implies, contain the rules that produce alternate views of those pages. Is it really necessary to repeat all of those default rules in each alternate stylesheet?

    At Risk of Repetition

    No, we don’t need to repeat all the default rules in each stylesheet. CSS provides the @import directive, which we can now employ to great effect.

    We’ll add the following to the top of our alternative stylesheets:

    @import url("default.css");

    This will include the default stylesheet in the alternate stylesheet, so we need only to override the specific page elements that we want to change.

    For example, to set the page elements marked with the 'menu' class to a nice orange colour, we’d add the following to our stylesheet.

    @import url("default.css"); 

    .menu  
    {
    background: #E5B786 /* nice orange */
    }

    In essence, this page will display the default styles, with the exception of any element that’s marked with the 'menu' class.

    Our alternative orange stylesheet makes the menu display like this:

    1420_orange

    We can overwrite any element in the default CSS and change its look completely — it’s just a matter of choice.

    Other Uses

    Until now, many developers have tended to employ this technique for fancy uses, but it can deliver real benefits in the area of accessibility.

    For example, our default CSS could contain the following:

    body{ font-size: 100%;}

    We could then add an alternative stylesheet with increased text size for those who are visually challenged, like so:

    Plus20.css could contain:
    @import url("default.css");
    body{ font-size: 120%;}
    }

    Simple!

    Frequently Asked Questions (FAQs) about CSS Simple Style Switcher

    How can I add more styles to the CSS style switcher?

    Adding more styles to the CSS style switcher is quite simple. You just need to create additional CSS files for each style you want to add. For example, if you want to add a ‘dark mode’ style, you would create a ‘dark.css’ file with the desired styling. Then, in your HTML file, you would add a link to this CSS file in the head section, just like you did with the original CSS file. Finally, you would add an option for this new style in your style switcher function, so users can select it.

    Can I use the CSS style switcher with dynamic websites?

    Yes, you can use the CSS style switcher with dynamic websites. The style switcher works by changing the CSS file that the HTML file links to, so it can work with any website that uses CSS for styling, whether it’s static or dynamic. However, you may need to adjust the JavaScript function to work with your specific website structure.

    How can I make the selected style persist across different pages?

    To make the selected style persist across different pages, you can use cookies or local storage. When a user selects a style, you would save their choice in a cookie or in local storage. Then, when the user navigates to a different page, you would check the cookie or local storage to see which style they selected, and apply that style to the new page.

    Is it possible to use the CSS style switcher with responsive design?

    Yes, it is possible to use the CSS style switcher with responsive design. The style switcher simply changes the CSS file that the HTML file links to, so as long as your CSS files are designed to be responsive, the style switcher will work with them.

    Can I use the CSS style switcher with a CMS like WordPress?

    Yes, you can use the CSS style switcher with a CMS like WordPress. You would need to add the JavaScript function to your theme’s JavaScript file, and the CSS files to your theme’s CSS directory. Then, you would add the style switcher options to your theme’s options page, so users can select their preferred style.

    How can I add a default style to the CSS style switcher?

    To add a default style to the CSS style switcher, you would simply set the default CSS file in the head section of your HTML file. This is the CSS file that will be used when the page first loads, before the user has selected a style.

    Can I use the CSS style switcher to change more than just colors?

    Yes, you can use the CSS style switcher to change more than just colors. You can change any CSS property, including font size, font family, layout, and more. You just need to include the desired changes in your CSS files.

    How can I make the CSS style switcher more user-friendly?

    To make the CSS style switcher more user-friendly, you can add labels or images to the style options, so users can see what each style looks like before they select it. You could also add a ‘reset’ option, so users can easily return to the default style.

    Can I use the CSS style switcher with a preprocessor like Sass or Less?

    Yes, you can use the CSS style switcher with a preprocessor like Sass or Less. You would write your styles in Sass or Less as usual, and then compile them to CSS. The resulting CSS files can then be used with the style switcher.

    How can I test the CSS style switcher to make sure it’s working correctly?

    To test the CSS style switcher, you can simply select each style in turn and check that the page updates to reflect the selected style. You should also test the style switcher on different browsers and devices to make sure it works correctly in all situations.