Understanding Series

Linking CSS

Topic status automatically displays here - do not remove.

Bookmark me!Bookmark this topic  Print me!Print this topic

By Colin Ramsden, month year.

Sample text.

How to Allow Your Visitors to Switch Between Alternate CSS Styles / Themes

by Christopher Heng, thesitewizard.com

Cascading Style Sheets provide webmasters a lot of control over their websites' appearance. One of its features is that you can specify different or alternate style sheets for a page. If your visitor prefers a particular design, or theme, that person can simply switch to that theme using their browser. This article describes how you can implement theme support, by giving your users the ability to switch between different styles on your website.

Note that there are two parts to the tutorial. This chapter deals with the Cascading Style Sheets ("CSS") component. It is complete in itself, and with it, you can already implement CSS switching support (or theme support) on your site for most modern browsers. The next chapter provides a dynamic way for the user to permanently set the theme for your site using JavaScript. It also adds support for browsers that do not have built-in support for switching styles.

This article requires you to have some knowledge of CSS. You don't have to be a guru or anything like that, but a little knowledge is needed otherwise you may be completely lost. You can read a brief introduction to CSS at http://www.thesitewizard.com/archive/css.shtml

Uses of Alternate Style Sheets / Themes

There are some reasons why you might choose to supply alternate style sheets for your users.

I'm not claiming that you must have alternate styles for your site because of these reasons. For most sites, an alternate CSS is an overkill. However, if you have established a community where users with very different demographics repeatedly return to your site, having alternative styles that appeal to different people may make your site more user-friendly.

Alternate CSS How-To

On most sites, web designers typically include a style sheet for their site using a link command like the following:

<link rel="stylesheet" type="text/css"
	href="http://example.com/css/style.css">

If you want to provide alternate style sheets for your site, you will need to give each style sheet a title, so that the browser will know that you are providing alternatives for your site. For example, if you want to provide two themes for your site, one called "blue" and the other "pink", you can specify them as follows, instead of the above example.

<link rel="stylesheet" type="text/css" title="blue"
	href="http://example.com/css/blue.css">
<link rel="alternate stylesheet" type="text/css" title="pink"
	href="http://example.com/css/pink.css">

Notice that the default style sheet that will be used is "blue". This is the preferred style sheet, and it is indicated by specifying a "rel" attribute of "stylesheet". The "pink" stylesheet is an alternate style that the user can choose. As you can see, it has a "rel" attribute of "alternate stylesheet". Another way of specifying that a particular style sheet is to be the default is to create a meta tag like the following:

<meta http-equiv="Default-Style" content="blue">

If you specify both the "alternate stylesheet" attribute value as well as the meta tag, the latter takes precedence. I suggest that you be consistent and stick to either one or the other method on all your pages. It'll make debugging and modifications easier, and reduce careless mistakes in the future.

Persistent Styles

Sometimes you may want a particular style sheet to be applied no matter which theme the user selects. Put all those common styles into a separate file, and include it without a title tag like this:

<link rel="stylesheet" type="text/css"
	href="http://example.com/css/common.css">

When no title tag is specified, the browser will always load that stylesheet. Such a style sheet is regarded as "persistent".

In other words, if a persistent style sheet is added to the example site above, the HEAD section will have the following declarations:

<link rel="stylesheet" type="text/css"
	href="http://example.com/css/common.css">
<link rel="stylesheet" type="text/css" title="blue"
	href="http://example.com/css/blue.css">
<link rel="alternate stylesheet" type="text/css" title="pink"
	href="http://example.com/css/pink.css">

The common.css style sheet will always be loaded. The default style sheet that will be used is the "blue" one. If the browser supports style switching, the visitor will be able to switch to the "pink" style as well.

Groups of Style Sheets

It is still possible to separate styles for different aspects of your web page into different files. For example, if you like to put your menu styles in a separate file from your layout styles, you can do it this way:

<link rel="stylesheet" type="text/css" title="blue"
	href="http://example.com/css/blue-menu.css">
<link rel="stylesheet" type="text/css" title="blue"
	href="http://example.com/css/blue-layout.css">
<link rel="alternate stylesheet" type="text/css" title="pink"
	href="http://example.com/css/pink-menu.css">
<link rel="alternate stylesheet" type="text/css" title="pink"
	href="http://example.com/css/pink-layout.css">

The browser will see all the stylesheets with a common title as one set of styles to be applied together.

How to Switch Alternate Style Sheets / Themes

Most modern browsers provide a way for your users to change style sheets for your site on-the-fly. For ease of reference, when I say below "View | Page Style", it means to click the "View" menu, then the "Page Style" item on the menu that appears. A list of style sheets that you can switch to will then appear.

For your convenience, I have provided an alternative to the default style for this page, so if you have one of the above browsers, you can try out the above commands to switch between my two style sheets. The alternate style sheet is merely the old style sheet for thesitewizard.com, which is, at this time, is being phased out.

Observe the following deficiencies in the built-in browser support for alternate style sheets:

The next chapter will provide a way to deal with these shortcomings.

Conclusion

Alternate style sheets allow you to add a sort of theme support for your website. This chapter deals with the CSS component of adding themes to your site. In the next chapter, I will discuss how you can use JavaScript so that the themes can be "sticky". That is, once the user selects a theme for your site, he/she will be able to view your whole site using that particular theme. The JavaScript will also add support for browsers that don't have built-in style switching.

 

How to Use JavaScript to Change a Cascading Style Sheet (CSS) Dynamically

by Christopher Heng, thesitewizard.com

It may be useful sometimes to provide your visitors with the option to change the appearance of your website. Perhaps you may want to provide theme support for your site. Or you may simply want to provide a bigger font size version of your site for older users who may not be able to read the small-sized text you use by default. This article describes how you can use JavaScript to dynamically change the cascading style sheets, or CSS, of your website.

Prerequisites

One of the assumptions I will make in this tutorial is that you know how to write HTML and CSS. You do not have to be highly proficient in either of these, but you should have at least a basic working knowledge. Some JavaScript knowledge is also necessary.

If you have not already done so, you may want to read the following articles as well. This guide was written as the part of a series of articles on how to provide alternate style sheets for your website and change them.

  1. How to Allow Your Visitors to Switch Between Alternate CSS Styles / Themes. It deals with the CSS aspect of switching style sheets.

  2. How to Use Cookies in JavaScript. Although not strictly part of the CSS style switcher series, the cookie management code provided in that article is used to preserve the theme selection that your visitors make on your site. Without setting a cookie, their CSS setting will not be retained when they go to the other pages on your website.

Steps to Adding a Style Sheet Switcher in JavaScript

Let's assume that we have the following style sheets defined in our HEAD section. This is the same code described and explained in the first instalment of this tutorial.

<link rel="stylesheet" type="text/css" title="blue"
    href="http://example.com/css/blue.css">
<link rel="alternate stylesheet" type="text/css" title="pink"
    href="http://example.com/css/pink.css">
  1. HTML Code to Provide a Way for Your Users to Choose the Style Sheet

    You will need to provide some way for your visitors to select the theme or CSS they want. There are many ways to do this, including the use of radio buttons, drop down selection boxes, normal submit buttons, text links, and so on. For usability reasons, you should not use things like checkboxes which suggests to users that they can simultaneously select a few themes and have them work together.

    Here's an example of HTML code using normal submit buttons.

    <form>
    <input type="submit"
      onclick="switch_style('blue');return false;"
      name="theme" value="Blue Theme" id="blue">
    <input type="submit"
      onclick="switch_style('pink');return false;"
      name="theme" value="Pink Theme" id="pink">
    </form>
    

    When the visitor clicks any of the radio buttons, the JavaScript onclick handler, switch_style(), will run. The function will be passed either 'blue' or 'pink' as its parameters, depending on which buttons is clicked. The words "blue" and "pink" correspond to the title attributes for the link elements referencing the style sheets.

  2. JavaScript Function to Change Style Sheets

    The actual JavaScript code needed to implement CSS style switching can be found below. If you find it difficult to cut/copy the code, it probably means that you are using IE 6. Please see my Copy/Paste Problems FAQ for a workaround.

    // *** TO BE CUSTOMISED ***
    
    var style_cookie_name = "style" ;
    var style_cookie_duration = 30 ;
    
    // *** END OF CUSTOMISABLE SECTION ***
    
    function switch_style ( css_title )
    {
    // You may use this script on your site free of charge provided
    // you do not remote this notice or the URL below. Script from
    // http://www.thesitewizard.com/javascripts/change-style-sheets.shtml
      var i, link_tag ;
      for (i = 0, link_tag = document.getElementsByTagName("link") ;
        i < link_tag.length ; i++ ) {
        if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) &&
          link_tag[i].title) {
          link_tag[i].disabled = true ;
          if (link_tag[i].title == css_title) {
            link_tag[i].disabled = false ;
          }
        }
        set_cookie( style_cookie_name, css_title,
          style_cookie_duration );
      }
    }
    function set_style_from_cookie()
    {
      var css_title = get_cookie( style_cookie_name );
      if (css_title.length) {
        switch_style( css_title );
      }
    }
    function set_cookie ( cookie_name, cookie_value,
        lifespan_in_days, valid_domain )
    {
        // http://www.thesitewizard.com/javascripts/cookies.shtml
        var domain_string = valid_domain ?
                           ("; domain=" + valid_domain) : '' ;
        document.cookie = cookie_name +
                           "=" + encodeURIComponent( cookie_value ) +
                           "; max-age=" + 60 * 60 *
                           24 * lifespan_in_days +
                           "; path=/" + domain_string ;
    }
    function get_cookie ( cookie_name )
    {
        // http://www.thesitewizard.com/javascripts/cookies.shtml
        var cookie_string = document.cookie ;
        if (cookie_string.length != 0) {
            var cookie_value = cookie_string.match (
                            '(^|;)[\s]*' +
                            cookie_name +
                            '=([^;]*)' );
            return decodeURIComponent ( cookie_value[2] ) ;
        }
        return '' ;
    }
    

    Note that this script includes the set_cookie() and get_cookie() functions from the How to Use Cookies in JavaScript article. For your convenience, I have already included those functions in the block of code above, so you do not need to copy and paste from that article. However, you may still want to read that article to understand the default settings and assumptions I make in my cookie code.

    The switch_style() function essentially iterates through all your link tags looking for a style sheet with the same title as the text specified in its argument (parameter). If it matches, it sets a special property, called disabled, to false, thus enabling that style sheet. In the meantime, all other relevant style sheets are disabled. The function ignores all persistent style sheets as well as any non-style-sheet link tags, such as those used for your site's favicon.

    When it finishes, it sets a cookie with the necessary information about the style sheet setting. By default, the name of the cookie is "style" and it is retained for 30 days. You can change this by altering the values of the style_cookie_name and style_cookie_duration variables at the start of the script.

    To ensure that the visitors' style sheet settings remain when they visit other pages of your site, as well as when they reload the page, you will also need to add an onload attribute to your web pages' body tag. For example, change <body> to the following:

    <body onload="set_style_from_cookie()">
    

    This causes the browser to run the set_style_from_cookie() function when the page is loaded. The function merely checks for the style-setting cookie, and if present, switches the style sheets accordingly. Otherwise, it does nothing.

Demo

You can check out how the script works using the test copy loaded with this page. To change between the current style sheet used on thesitewizard.com and the older version, simply select the appropriate button below.

Note that the code used for this demo sets a cookie called "demo_theme" in your browser that is valid for only 1 day. The cookie will contain either the word "blue" or "grey", depending on which button you click. Your setting will only affect this page, and no other page on this site, since none of the other pages include the style switcher JavaScript code.

Browser Compatibility

The above code has been tested in IE 6, 7, Opera 9, Firefox 2 and Safari for Windows 3.1. It should (hopefully) work for all newer browsers as well.

Conclusion

This chapter concludes the series on creating a theme switcher, to change style sheets, using both CSS and JavaScript.

 

 

Who am I? > find out more

 


See Also

Jump to site home page Lotech Solutions' Tips, Tricks, and Procedures

Back to Top