For a simple listing page I was working on, I needed some sort of ribbon to depict a status for that listing item. Having seen lots of ribbons on various web pages I went shopping for some pre-made nice looking ribbons. I was using Sass as a css preprocessor and sass-bootstrap for rapid prototyping so sure enough, the first google result for sass bootstrap ribbon yielded a rejected bootstrap issue with a working jsfiddle for a nice green ribbon.
And it produces a nice looking ribbon stuck to the top right of the page:
With some minor modifications I adapted the css to apply the ribbon to every item on the listing instead of the whole page. Also, I needed several colored ribbons representing different listing states. The result was pretty spiffy:
But the css was growing to be a huge mess of repeated and inflexible code. For each new color needed, I had to find the right gradient and text colors, and repeat some css in an ever growing exercise of copy/paste. This was becomming pretty ugly, pretty fast:
Let’s refactor this code using the some nice Sass features and some ready-made mixins provided by sass-bootstrap.
Removing vendor prefixes
The low hanging fruit is the vendor prefixes that we can reduce by using some sass-bootstrap mixins. You can get a list of bootstrap provided mixins in the _mixins.scss file. Mixins are like modules of code that can be included in other rules. They can even take arguments to further customize the included code. Take for example the sass-bootstrap rotate mixin:
One annoyance I faced when adding other ribbon colors for different status, was that I needed to pick three colors to define the new ribbon: a base color, a lighter color for the gradient and a darker color for the text and ribbon folds. Sass provides some functions to do color math, like lighten and darken that we could use to avoid having to specify three different colors.
So I created a mixin that receives a base color, calculates both a lighter and darker versions of that color and assigns the resulting colors to variables that are used in the relevant places. Also used the & operator to reference the parent selector of the rule this mixin will be included in.
There are probably other improvements to this code, but I’m pretty happy with the results. Once you start using a css preprocessor like Sass, and realizing its power you cannot go back to plain css anymore.