While redesigning the thoughtbot site, I gave myself a challenge: create an easily editable and maintainable baseline grid. I figured that there had to be an easier way to do this with Sass than with plain old CSS.
I started off going to the wonderful modulargrid.org to create my grid. I grabbed the png and threw it into the background so I could be certain everything is aligning perfectly. Then I created 3 variables based on the grid; one for the column unit width, the gutter width and line-height. This made things conceptually easier for me instead of trying to balance numbers.
$line-height: 20px; // line-height for the site
$unit: 60px; // column size
$gutter: 25px; // gutter size
Getting some layout
Almost as soon as I had started, Sass 3.1 came out touting functions and in the change log examples I found this gem:
@function grid-width($n) {
@return $n * $unit + ($n - 1) * $gutter;
}
This function calculates that width of the column by giving it the number of units you want it to span. Now all I needed to do is drop in grid-width() for any width and it will conform to the column sizes in my grid. For example, I wanted the grid to be 12 units wide, so on the wrapper for the site I put:
width: grid-width(12);
Of course this isn’t always perfect, the box model adds padding and the border to the width of the box and it breaks the grid. Bah. But Sass is wonderful and can do simple math and can apply that even to functions. So on a box that spans 4 columns but has 20px of padding on both sides I can subtract the padding to get the correct width of the column.
padding: 20px;
width: grid-width(4)-(20px*2);
Dealing with the baseline
The background image that I had for the grid also gave me guidelines for where the baseline should fall. Then all vertical spacing for the design uses the line-height variable. Everything from padding to the margin to the height of the images can all be declared with the line-height variable and some multiplication.
height: $line-height * 6;
margin-top: $line-height * 3;
padding: $line-height;
Again, I ran into scenarios with the box model where I didn’t want to use the
whole line-height. These changes and exceptions were easy to accommodate with a
little math just like the grid-width()
.
padding: ($line-height*2)-(1) 0; // account for 1px border
Throughout all the Sass I've successfully avoided doing any real calculations and feed Sass a bunch of math problems. Updating and maintaining the layout is easy, anyone who goes into the Sass won’t have to figure out what the width of a 3 columns would be. It also has the ability to be easily adaptable to having a fluid layout.
Bonus
The grid-width function has also been incorporated into Bourbon, our default set of mix-ins and functions. Use variables $gw-column and $gw-gutter and then you are all set. No need to set up the function.
If you’d like to get some more Sass and advanced HTML & CSS tricks come to my workshop on Sept. 26th & 27th.