Skip to content

Instantly share code, notes, and snippets.

@AllThingsSmitty
Created April 6, 2015 13:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AllThingsSmitty/05a067f3257286adaced to your computer and use it in GitHub Desktop.
Save AllThingsSmitty/05a067f3257286adaced to your computer and use it in GitHub Desktop.
Calculating grid column widths
/*
First: determine the number of columns, ex.: 12
Second: determine the width of a single (1/12) column using the following formula:
scw = (100 – (m * (mc – 1))) / mc
Where:
scw = single column width
m = margin (1.6%)
mc = maximum columns (12)
Ex.: scw = 6.86666666667%
Lastly: use the scw to calculate the rest of the column widths using the following formula:
cw = (scw * cs) + (m * (cs – 1))
Where:
cw = column width
scw = single column width (6.86666666667%)
cs = column span (1-12)
m = margin (1.6%)
Applying this formula for each of the 12 columns results in the following CSS:
*/
.column-1 {
width: 6.86666666667%;
}
.column-2 {
width: 15.3333333333%;
}
.column-3 {
width: 23.8%;
}
.column-4 {
width: 32.2666666667%;
}
.column-5 {
width: 40.7333333333%;
}
.column-6 {
width: 49.2%;
}
.column-7 {
width: 57.6666666667%;
}
.column-8 {
width: 66.1333333333%;
}
.column-9 {
width: 74.6%;
}
.column-10 {
width: 83.0666666667%;
}
.column-11 {
width: 91.5333333333%;
}
.column-12 {
width: 100%;
}
@BigglesZX
Copy link

Hello from the future! This was super helpful, thank you – surprisingly not a lot of search results on this technique out there, unless my google-fu just sucks. This formula also works with fixed-width gutters if you use calc. Here's a SASS function I wrote for this, in case anyone else ever stumbles across it.

@function grid-span($span: 1, $of: 4, $gap: 16px) {
    // Calculate percentage equivalent of column width within a grid layout
    // source: https://gist.github.com/AllThingsSmitty/05a067f3257286adaced
    @return calc((((100% - ($gap * ($of - 1))) / $of) * $span) + ($gap * ($span - 1)));
}

I was also able to adapt this calculation to produce percentage margins to pull/push an element left/right by a specified number of "columns". Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment