*.dannyg

Decoupling CSS Files (Skinning)

Dec
14

It can be very useful to decouple CSS files from each other without reusing classes.  In some cases you might want a designer to focus on handling the coloring items and not have control over positioning.  This can be very painful especially if most of your CSS classes have already been defined.

This methodology allows you to dynamically create some “Skin” classes based off predefined ones.  I have created two simple helper functions.  This tutorial requires that you use jQuery.

function applySkin() {
    _skinObjs($("body"));    
    _skinObjs($("div"));
    _skinObjs($("span"));    
    _skinObjs($("a"));
}
 
function _skinObjs(objs) {
    for (var i = 0; i < objs.length; i++) $(objs[i]).addClass($(objs[i]).attr("class") + "-Skin");    
}

This will essentially, add a “–Skin” class to every body, div, span, and anchor tag on your page (feel free to add additional tags as necessary). 

Now you can remove what information you want repeated.  So let’s say that you have a Site.css stylesheet and you want to remove some stylistic definitions to a separate file (coloring for example).  To continue on that example, take this sample html code.

<html>
<head>
<title>Sample Page</title>
<link href="Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div class="MainTitle">Hello World!</div>
</body>
</html>

 

Take a look at the Site.css, notice how the color information is in the same file.

.MainTitle 
{
    font-size: 32pt;
    position: absolute;
    top: 100px;
    left: 100px;
    background-color: #fea130;
}

So what I need to do now is to create a separate file.  Let’s call it Site-Skin.css.  I will append to my class “-Skin” as seen earlier.  I also need to remove it from my Site.css file.

Updated Site.css

.MainTitle
{
    font-size: 32pt;
    position: absolute;
    top: 100px;
    left: 100px;
}

 

Site-Skin.css

.MainTitle-Skin
{
    background-color: #fea130;
}

Now I need to specify in my HTML code the link to the particular “-Skin” I want to use.  Let’s say that I’m using a scripting language like ASP.NET, I could put the skins in different folders and dynamically change the decoupled CSS file.

<%@ Page Language="C#" %>
<html>
<head>
<title>Sample Page</title>
<link href="Site.css" rel="stylesheet" type="text/css" />
<link href="<%=Skin_Folder%>/Site-Skin.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div class="MainTitle">Hello World!</div>
</body>
</html>

 

Now if you look below you can see my folder structure has multiple Site-Skin.css files.

image

This is very powerful as your designer can very easily work on the Skin while you work / or someone else works on positioning and other features of the styling process.

Technorati Tags: ,,,