Skip to main content

Using LESS to Create a Grid System



The last couple of custom Drupal themes I created called for a very simple grid system to be included in the project.  For example, lets say we needed to work off of a grid of 12 columns.  Normally we would need to go through and take the outside width of the parent container and divide each column up by this width and set each column by hand to get the exact width of each column in our grid.   This seems like a rather tedious method that probably would require me or some poor soul working with me to rework many times over the course of project.  So, I thought there has to be a better to dynamically create this gird system, there had to be a way to create a function that takes the number of columns and divides each column up and sets the appropriate width whenever grid needed to be changed.  Well, luckily Bootstrap does something close to this already, so I gleamed a bit from what Bootstrap was doing and created my own grid function to produce the CSS dynamically from LESS.  See the grid code below.  Simply set the number of desktop columns and gutter size and this will output CSS ready for you to use in your HTML grid system after it is compiled.

/*       Grid LESS                                   */
/*                                                   */
@grid-gutter:    20px;
@desktop-grid-columns:   12;
// helper class, will never show up in resulting css
// will be called as long the index is above 0
.loopingClass (@index) when (@index > 0) {
      // your resulting css
      position: relative;
      float: left;
      width: percentage((@index / @desktop-grid-columns));
      min-height: 1px;
   // next iteration
  .loopingClass(@index - 1);
// end the loop when index is 0
.loopingClass (0) {}
// "call" the loopingClass the first time with highest value
.loopingClass (@desktop-grid-columns);
// the styles inside the grid
   margin-left:  (@grid-gutter / 2);
   margin-right: (@grid-gutter / 2);
// kill both margins
   margin-left: 0;
   margin-right: 0;
// kill left margins
   margin-left: 0;
// kil right margins
   margin-right: 0;

The following LESS will be compiled to the CSS below. 


Member for

3 years 9 months
Matt Eaton

Long time mobile team lead with a love for network engineering, security, IoT, oss, writing, wireless, and mobile.  Avid runner and determined health nut living in the greater Chicagoland area.



Thu, 08/06/2015 - 02:53 PM

Your dotted background scared me away from reading the article. I suggest just using white or a very light grey (#eee)