OdeToCode IC Logo

Colorful ASP.NET Themes

Thursday, September 1, 2005

The Colorful Web Site Starter Kit on .NET Treats and Tricks is a nice piece of work (via Cindy). On the site you’ll find a find 8 ASP.NET 2.0 Themes you can download and use. The themes not only look nice but have a great design.

For instance, Erika used styles from a CSS file whenever possible. I’ve seen some grumbling that themes and skins in ASP.NET 2.0 are an evil plot to subvert web standards, when actually themes provide a great infrastructure to manage multiple sets of CSS files. Select a theme for a page and the runtime will automatically inject link tags for all of the stylesheets in the chosen theme directory.

There are some server controls that are just not easily styled: WebPartZone, Calendar, GridView, for instance. The colors and other visual properties of these controls are set with a skin file in each theme (see my ASP.NET 2.0 Themes article for more details on themes and skins).

There is also an Images subdirectory for each theme. Images can be tricky with themes, and tricky with master pages, and even trickier with themed pages using a master page.

You never want to use an absolute path to an image in a theme directory. Absolute paths break easily, and you’d have to change them with your own code if you want to switch themes. Always use relative paths. For instance, here is a snippet from the default.css in one of the themes.



    background-image: url(Images/bar.jpg);

    text-align: right;

    height: 24px;


When the above reaches the client, the browser will be smart enough to request bar.jpg from the App_Themes/MSN_Blue/Images directory (when MSN_Blue is the selected theme).

What about images you want to vary by theme on a page, or on a master page? We know the runtime will do some URL rebasing for paths in a master page (read near the end of ASP.NET 2.0 Master Pages for more details), but that doesn’t help in rebasing an image’s src attribute from one theme to the next if you have hard coded the full path to an image file in a theme.

The easy solution is the SkinID attribute for server side controls. You can only have one default skin for a control, but multiple skins are available with a skin id. For instance, the colorful web site starter kit uses two image skins, identified by SkinID.

<asp:image runat="server" Imageurl="Images/logo.jpg" skinid="logo" />

<asp:image runat="server" Imageurl="Images/bullet.jpg" skinid="bullet" />

Notice the src uses relative paths. The logo on the master page uses the following:

<asp:Image ID="Image1" runat="server" skinid="logo"/>

With this approach you can switch the logo for a web site just by using a different theme. Sweet.