found drama

get oblique

using lists to hold parameters for Compass functions

by Rob Friesel

This past weekend at Vermont Code Camp, I caught Mike Fowler’s presentation, “Crafting Scalable Stylesheets”. In that presentation, he discusses this notion of “smart” variables (slides 32 through 35), wherein we provide an argument to a mixin (or even just a simple @if statement), and then based on that argument’s type-of value, we select a code path for how to handle that argument.

In Mike’s example (on slide 35), we have a variable $page_fill which is either a color value, or a list of colors. If we have a list, then we’re going to use its values as the arguments to the linear-gradient function from Compass; otherwise we will use the singular color value for a flat background-color.

I had never thought to use a solution like this, but it was pretty clever and (even better) it was remarkably obvious what was happening when you looked at the code. A win all around. The only part that made me sad was that it appeared that you needed to explicitly pull out each value from the list (using the nth function from Sass), and then invoke the linear-gradient function.

Why did this make me sad? It seemed too brittle. What if you wanted a gradient with more than two colors? Did you then need to enter a nested @if to look at the length of the list? So (during the presentation) I asked Mike if he had tried it with the lists by themselves. “Could you just give the list to linear-gradient as-is?” He said he wasn’t sure.

So I went home and tried it. My results were mixed, but the short answer was: Actually, that does kinda work. Assuming you have some Sass like this:

It will compile, and you’ll get some CSS like this:

Granted, it wasn’t a perfect solution to the problem. I couldn’t quite get it to work with the radial-gradient function, and Compass balked when I had list items that were missing any color information (e.g. «red», «#eee», and «#ffc56c 10%» were all acceptable, but «top left» was not)–but overall, just passing in the list dramatically simplified Mike’s example. (At least for “trivial” or “simple” uses of linear-gradient.)

About Rob Friesel

Software engineer by day. Science fiction writer by night. Weekend homebrewer, beer educator at Black Flannel, and Certified Cicerone. Author of The PhantomJS Cookbook and a short story in Please Do Not Remove. View all posts by Rob Friesel →

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*