The joy of LESS

I’ve been using LESS quite a lot of the last few years, especially combined with Bootstrap. Writing bog standard CSS feels quite long winded and painful now. Today I was reminded quite how much I like it when doing some categorisation for a site. You know the problem, lots of very similar lines of CSS with one differing attribute (in this case, colour). In standard CSS, you’d end up hard coding category names in multiple places, i.e:

.myDiv .my-category-one a, .myDiv .my-category-one h1 {color:red;}
.myDiv .my-category-two a, .myDiv .my-category-two h1  {color:blue;}
.myDiv .my-category-three a, .myDiv .my-category-three h1 {color:green;}

etc..

Behold, the mixin. Save yourself some time.

// Category Mixin
.category(@name, @colour){
  .myDiv [email protected]{name} {
    a {color: @colour}
    h1 {color: @colour}
  }
} 
// Create Categories
.category(my-category-one, red);
.category(my-category-two, blue);
.category(my-category-three, green);

Why is this better? Well, to add another Category is simply a case of adding

.category(my-next-category, @brand-primary);

Anything from my Mixin, like H1 and a CSS selectors get auto applied. Make the change once, done. Need to add more selectors to your category? Add them to the mixin. Simples. Note the variable output of “name” – [email protected]{name} which will create .my-category-one (or whatever you’ve passed in).