Make Your CSS Smarter with Sass
These days, there is no shortage of “CSS with variables” solutions available to web developers. Two of the more popular frameworks available today are LESS and Sass. To be honest, these two options are not all that different (as of v3 of Sass, at least). Both are supersets of CSS (valid CSS is valid LESS and valid Sass). Both are Ruby gems, and both share a similar syntax. Though I’m sure there are subtle differences between the two, I leave it as an exercise for the user to delve into those finer details (maybe you can mention your findings in the comment section?).
I’ve tended to lean towards Sass; the language is a part of the HAML gem, a templating system that allows developers to write templates in a syntax similar to Ruby. I’ve spent a small amount of time with HAML, and that probably explains why I’m partial to Sass. I’ll walk you through some of Sass’s features and provide a possible solution to leveraging Sass in ASP.NET applications.
How many times have you written the following?
Granted, my color choices are a bit underwhelming, but that aside, this is certainly not new territory! With Sass, we can utilize nested styles to better organize our styles. Combining the power of nested styles and another one of Sass’s features, parent references, we can write the same code in Sass as:
In the above example, we’ve used the & character to reference the parent style element (in this case, anchor elements) Now, as far as total line count, we haven’t really saved ourselves much (1 lousy line). What we have gained, however, is a deeper abstraction of our various elements’ styling, which is ultimately what we as developers try to do day in and day out.
Nesting styles alone offers significant leverage, but combining it with the ability to declare variables adds a level of maintainability currently not possible with regular ol’ CSS. Variables in Sass are prefixed with the $ character; variables can be assigned to text, numbers, etc. WordPress theme writers could really put Sass to work for them:
Theme creators might be underwhelmed by my previous example, especially since they can do a “Find all and replace” to change colors out; where they might scratch their heads is Sass’s built-in functions and math operators. These abstractions allow for easy color manipulation and layout calculations, all handled within the style sheet.
Of all of Sass’s features, the one probably most alien to the average person writing CSS is mixins. For the non-Rubyists out there, mixins is a feature of Ruby that offers a form of inheritance that looks more like composition. You can read more about it at Pragmatic Programmer’s Guide. In Sass, mixins allow the developer to define small portions of CSS styling which can then be imported into other styles. An example will make this more clear:
When the Sass styles are “compiled” down to regular ol’ CSS, the above looks something like this:
… And Much More!
There are a number features available in Sass that I haven’t touched on, including the ability to import other Sass stylesheets, as well as the ability to pass arguments to your mixins. If you’d like to learn more about Sass, I’d recommend just visiting the site; it undoubtably does a better job describing what it does and examples that better show its utility. One of the interesting things I thought would be cool to explore is incorporating Sass into ASP.NET web applications by adding the Sass compilation step to the build process in Visual Studio/MSBuild. I’ll outline the steps to getting this working quickly below.
Sass + ASP.NET
If you’re developing an ASP.NET app, you’re probably working in Windows, so I’m going to target this walkthrough at Windows folks; if you’re doing work in Mono and you’d like instructions on getting this working with Monodevelop or the like, let me know in the comments and I’ll see what I can whip up…
If you don’t already have Ruby installed on your machine, you’ll want to install that, as Sass is a Ruby gem. For a quick and painless install, I’d just go to the RubyInstaller download page, get the newest version (at the time of writing, 1.9.2), and run the installer.
You’ll want to make sure you check the checkbox asking if you want to add Ruby to the Path. Otherwise, it’s a bit of a pain to use Sass from command line.
Installing the HAML/Sass gem
Once the Ruby installer has finished, open up a command prompt and enter the following command:
gem install haml
This command tells Ruby Gems, a package manager that allows you to install, update, and keep track of the various Ruby libraries (gems), to install the HAML gem; Sass is a part of the HAML gem, so once that has finished we’ll be set as far pre-reqs. As an aside, if your team has a build server, you’ll obviously want to get Ruby/Sass installed on the build server so that it can transform the Sass stylesheets into CSS stylesheets when it comes time to build. In short, you’ll probably want to install Ruby/Sass locally on your development machine (if you’re doing quick builds to test functionality), as well as the server where the “official” builds are done.
Visual Studio/MSBuild Integration
Now that we’ve got Sass installed, we can begin to leverage it in our ASP.NET web apps. Let’s start by creating a new web application in Visual Studio:
Create a new folder at the root of the site called “css”. Right-click on that new folder, and choose “Add -> New Item.” Choose “Text File” as the filetype and enter “style.scss” as the filename:
One unfortunate side effect of this is that since we’re choosing a filetype of “Text File,” we’re not going to get any of the pretty syntax highlighting we know and love in VS. Furthermore, we can’t easily associate file extensions with the CSS Editor. I’ve seen examples on the web of how to do this, but the other caveat is that the code completion engine gets pretty confused by the nested styles, mixins, etc. of Sass, so it’s probably easiest just to leave it be. If you’re really in need of some syntax highlighting, I’d recommend editing the Sass stylesheet outside of VS using Notepad++.
There’s a nice command built into Sass that will make Sass watch a file or directory for changes to Sass files and automatically compile them as they are updated. This could be helpful while coding. “sass –watch [PATH_TO_STYLE_DIR]” will do this for you.
Using the watch command is helpful, but it won’t ensure that your CSS files are always up-to-date, especially if other developers are working on the codebase. We’ll add a post-build event to our project file so that we can ensure our CSS file is always up-to-date when we build and/or deploy. Right-click on the web application project file in the Solution Explorer and choose “Properties.” In the Properties window, click the “Build Events” tab. In the post-build event command line textbox, enter the following:
sass “$(ProjectDir)css*.scss” “$(ProjectDir)css*.css”
This command will tell Sass to compile all the Sass stylesheets in the “css” folder into CSS files. This might not be the optimal command if you’re utilizing the @import functionality in Sass and don’t actually want to compile ALL Sass files in that directory. Edit this command to meeet your needs. When you’re done, be sure to save.
Before we get on with it, I’m going to add a “style.css” file to the “css” folder. This is really just going to serve as a placeholder file. We won’t directly edit it, but it will make it easier to deploy/version control the files if we add it anyway. Right-click on the “css” folder in Solution Explorer and choose “Add -> New Item”; choose the stylesheet filetype and enter “style.css” as the filename.
Now that we’re squared away, let’s test out what we’ve done. Open up the “style.scss” file and enter some Sass:
One of the beauties of hooking Sass into the post-build is that we’ll essentially get compile-time validation of our Sass. If you try to build and get errors, check that Ruby is in the path, that the HAML gem is installed. Double-check the post-build event command line text; lastly, make sure you Sass is legal! If you’ve followed the above, you shouldn’t have a problem.
Once we’ve verified our Sass is building correctly, let’s put it to work. Open the “Default.aspx” file and add a stylesheet link in the document HEAD to the “style.css” file:
<link rel=”Stylesheet” type=”text/css” href=”css/style.css” />
While you’re at it, insert a <p> element into the body of the webform and put some text in it. Launch the debugger and bask in the glory! Feel free to adapt this method to suit your needs; everybody’s situation is different!
Sass + ASP.NET FTW
Hopefully this post has piqued your interest in Sass and other CSS frameworks. I’ve given some direction on integrating Sass into ASP.NET applications. Integrating existing applications would be almost as trivial, as valid CSS is of course valid Sass. Leveraging the abstractions that Sass allows can help to make for more maintable and more concise styling.
I’ve zipped up the sample web app we created above, you can get it here. Enjoy!