Build A Simple Style Switcher in CSS

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.

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:

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:

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: