Last Updated: February 25, 2016
·
475
· nuck

%-columns and em-baselines in <20 lines of LESS

A simple and responsive alternative to heavyweight grid frameworks that makes no assumptions and adds no styles, just two mixins.

Mixins

.font-scale (@scale: 1) {
    @size: (@scale * @text-fontsize);
    font-size: @size;
    line-height: (ceil(@size / @text-lineheight) * (@text-lineheight / @size));
}

.columns (@cols: 1, @margins: @columns-gutter) {
    width: ((@cols / @columns-count) * 100% - @margins);
    margin-left: (@margins / 2);
    margin-right: (@margins / 2);
}
  • .font-scale(@scale: 1) sets font-size and line-height on a simple multiplier of a base font size (1em normally), automatically latching the line-height to the nearest baseline grid multiplier that can contain it. It does some math to maintain the baseline grid despite the fact that ems on an element with increased font size will be larger than normal.
  • .columns(@cols: 1, @margins: @columns-gutter) sets the width plus left and right margins for an n-column grid. Container can be whatever, since we're percentage-based it's all relative to that.

Settings

@text-fontsize: 1em;
@text-lineheight: 1.5em;

@columns-count: 12;
@columns-gutter: 1%;
  • @text-fontsize is the base font size for the entire page, generally 1em, but you can change it if you want
  • @text-lineheight is the height of the baseline grid - generally 1.4-1.5x the font size will work
  • @columns-count is the number of columns in the grid
  • @columns-gutter is the space "between" columns (in percent) -- technically we apply it to the margins of the column (half on either side) and subtract it from the width

Caveats

  • To use padding and borders on columns, you have to use box-sizing: border-box
  • You should wrap the math in round() since LESS likes to spit out way too much precision. 3-4 points past the decimal is usually more than enough.