CSS File Minification in C#

CSS files are usually pretty riddled with white space, extra characters, etc. that are not needed to work but is simply there so we can go in and read the file. And to be honest we need to keep them that way so that we can go and modify them. It's an endless fight between size vs readability.

So how do we go about getting the best of both worlds? Well you can add a step to your production cycle and use one of the many CSS minification apps out there (such as the YUI Compressor). And they do a good job but it's another added step, you have to make sure you run it on every CSS file, etc. I find them to be a pain personally. That leaves you with minifying the file at run time. And to be honest, it's rather simple and can be done with the following function:

namespace Utilities
{
    /// <summary>
    /// CSS utility class
    /// </summary>
    public static class CSS
    {
        #region Static Public Functions
        /// <summary>
        /// Strips whitespace from a CSS file
        /// </summary>
        /// <param name="Input">Input text</param>
        /// <returns>A stripped CSS file</returns>
        public static string StripWhitespace(string Input)
        {
            Input = Input.Replace("  ", string.Empty);
            Input = Input.Replace(System.Environment.NewLine, string.Empty);
            Input = Input.Replace("\t", string.Empty);
            Input = Input.Replace(" {", "{");
            Input = Input.Replace(" :", ":");
            Input = Input.Replace(": ", ":");
            Input = Input.Replace(", ", ",");
            Input = Input.Replace("; ", ";");
            Input = Input.Replace(";}", "}");
            Input = Regex.Replace(Input, @"(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,}(?=&nbsp;)|(?<=&ndsp;)\s{2,}(?=[<])", string.Empty);
            Input = Regex.Replace(Input, "([!{}:;>+([,])s+", "$1");
            Input = Regex.Replace(Input, "([^;}])}", "$1;}");
            Input = Regex.Replace(Input, "([s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
            Input = Regex.Replace(Input, ":0 0 0 0;", ":0;");
            Input = Regex.Replace(Input, ":0 0 0;", ":0;");
            Input = Regex.Replace(Input, ":0 0;", ":0;");
            Input = Regex.Replace(Input, "background-position:0;", "background-position:0 0;");
            Input = Regex.Replace(Input, "(:|s)0+.(d+)", "$1.$2");
            Input = Regex.Replace(Input, "[^}]+{;}", "");
            Input = Regex.Replace(Input, "(/" + Regex.Escape("*") + ".*?" + Regex.Escape("*") + "/)", string.Empty);
            return Input;
        }
        #endregion
    }
}

The code above strips out all unnecessary whitespace from the string that is entered, removes comments, etc. We could even go in and reduce the size of hex colors if we really wanted, but I'm leaving those alone as the space savings is rather negligible. So what we would do, is set up an HTTPHandler that takes in the path to a CSS file. The handler loads the file and then calls the function above with the resulting string being the value that we return to the user. We could even improve the handler further by allowing it to receive multiple file locations, con cat the file content together and then feed it into the function above. Anyway, definitely give it a try, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 6/2/2009 at 8:43 AM
Tags: , , ,
Categories: C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Resolution based CSS Selector for ASP.Net

Usually when you create a style for a website you make sure that it shows well at multiple resolutions, multiple browsers, etc. However sometimes, there's nothing you can do to force certain things onto a 640x480 display. For instance, my website stays rather static in the middle of the screen and is optimized for 1024x768 resolution on up. I'm rather lazy so I'm not going to go and make it look fantastic for 800x600 or 640x480 displays, plus very few programmers use those resolutions today (and that's really the only group of people that would bother coming here) so the pay off would be small. Most people are making websites for the average person though and need to worry about such things. So what do we do?

Well there are actually two cases that we need to worry about:

  1. People using mobile devices (Blackberry, etc.)
  2. People using a regular web browser.

The first instance is rather easy to detect. Simply use the Request.Browser.IsMobileDevice to determine if it is a mobile device that is making the request and set the theme/CSS appropriately for those instances. The second instance is a bit trickier. We have Request.Browser.ScreenPixelsWidth and ScreenPixelsHeight, but I've never been able to have it give me accurate information. So that leaves us with javascript to find out the information:

 

if(screen.width==800)
{
      document.getElementsByTagName("link")[0].href="800CSSFile.css";
}

 

OK, so it's actually quite easy to find out the information. So you can simply go in and add something like that to each file, or you can add the control that I've created below:

ResolutionCSSChangerExtender.zip (1.73 kb)

All you need to do is call it with a list of screen widths you're interested in and a list of CSS files separated by commas and it will do the rest. That's it, really nothing to it. Anyway, download the code, give it a try, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 7/7/2008 at 9:21 AM
Tags: , ,
Categories: AJAX | ASP.Net | Web Design
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Quick CSS trick for drop down menus

Let's assume that you didn't want to use one of the many pre made solutions for creating a drop down menu. And let's assume that you wanted it to be completely CSS (ie no javascript). Well, it's possible and here's how you accomplish it:


<div class="Menu"><ul>
<li class="Header">Head item</li> 
<li class="DropDownItem">Item 1</li>
<li class="DropDownItem">Item 2</li>
</ul></div>

Now we set up our CSS:


.Menu ul .DropDownItem
{
display:none;
}


.Menu ul:hover .DropDownItem
{
display:block;
}


.Menu
{
position: absolute;
}

That's all there is to it. All that you end up having is a couple of lists and whenever the mouse hovers over the list, it makes the hidden items visible. Also we need to make sure to make the menu positioned absolutely. Otherwise we screw up the positioning of all of the other items. But that's all there is to it. No javascript, nothing special, just a drop down menu with minimal work, although to be honest I'm lazy and would just use the pre made solutions... Anyway, use the code, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 6/16/2008 at 2:21 PM
Tags: ,
Categories: Web Design
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed