Dynamic CSS

Recently, while working on a new ASP.NET MVC website for Glenmore Park Anglican Church, I have found myself wishing for the same server-side text substitution in CSS files that we enjoy in ASPX files (the <%= … %> construct).

It seems that this is much easier to accomplish that it may appear at first.

Create an ASP.NET page (say, site.aspx), and below the Page specification, include your CSS tags.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="site.aspx.cs" Inherits="Content.CSS.site" %>
body {
    margin: 0px;
    font-family: 'Trebuchet MS', 'Lucida Grande', Verdana, Arial, Sans-Serif;
    background-color: #666666;
    background-image: url(<%= AppHelper.ImageUrl("MyImage.png") %>);

Now comes the tricky bit.  In the code-behind file, include the following:

protected void Page_Load(object sender, EventArgs e)
    Response.ContentType = "text/css";

Now just use site.aspx rather than site.css in your CSS links, and voila!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s