Make Your Life Easier—Write Less CSS

As far as programming languages go, CSS is the least fun to write. Without variables, mixins or mathematical operations, it can be very time-consuming to write CSS and a nightmare to make changes.

Introducing… Less: Leaner CSS.

Less is a gem that helps alleviate the pain of writing CSS by making it DRYer and far more intuitive.

To install the gem, simply run:

sudo gem install less

You’ll also want to use the less-for-rails plugin by August Lilleaas:

script/plugin install git://github.com/augustl/less-for-rails.git

Usage

To create a stylesheet using Less, simply add a new file to your /stylesheets directory with the format “.less”. Eg, application.less. Write your CSS in this file instead of application.css – the less-for-rails plugin will ensure application.css is updated as you make changes.

Previously, a snippet of CSS may have looked something like this:

div#content{
  width: 80%;
  margin: 0 auto;
}

div.comment{
  border: thin solid silver;
  border-bottom: thick solid #BEBEBE;
  background: #E5E5E5;
  width: 80%;
  margin: 0 auto;
  height: 100px;
}    

.comment p{
  margin-top: 5px;
  font-family: sans-serif;
}

.comment p a{text-decoration: none;}

form#new_comment{
  border: thin solid silver;
  border-bottom: thick solid #BEBEBE;
  background: #E5E5E5;
  width: 80%;
  margin: 0 auto;
}

With Less, this can be simplified to:

@comment_height: 100px;
@inner_width: 80%;
.centered{
  width: @inner_width;
  margin: 0 auto;
}

.comment_borders{
  @comment_background: #E5E5E5;
  border: thin solid silver;
  border-bottom: thick solid (@comment_background/1.2);
  background: @comment_background;
  .centered;
}

div#content{.centered;}

div.comment{
  .comment_borders;
  height: @comment_height;
  p {
    margin-top: @comment_height/20;
    font-family: sans-serif;
    a {text-decoration: none;}
  }
}
form#new_comment{.comment_borders;}

In this example, the variable @comment_height is set to 100px and the margin-top value for p tags within a .comment div is set to @comment_height/20. If we change the height of .comment this margin will also change so that it’s always a 5% of the total height.

Another really cool feature is the ability to apply mathematical operations to colour values. So if we have a div with background-color #7f7f7f, we can multiply this value by two for the text-color property, meaning the text will always be twice as bright as the background-color (up to the #FFFFFF limit).

The class .comment_borders is a mixin. Mixins allow you to store commonly shared values in one place. These can then be included into any other css instruction by simply writing the class name followed by a semicolon.

For more information, check out the Less homepage.

Written by

Photo of Gavin Morrice
Gavin Morrice

Software engineer based in Scotland

Work with me

Need help with some code?

In my free time, I like to help people improve their code and skills on Codementor.
Contact me on Codementor