Short version: Instead of precompiling math for our grids we can do it live in the browser using CSS variables, thus saving us a LOT of lines in CSS (...in the future. I'm looking at you Explorer)
Here are two elements, lets pretend they're a sidebar and an article element
No grid classes classes like
col-2
or
grid-12_lg-8_md-6_sm-4_xs-2
. Instead we're using
a variable on each element.
Here's whats going on:
First off we need to define number of columns and the width of our grid gutters.
:root{
--column: 8;
--gutters: 10;
}
For our own sanity we'll use flexbox.
.row{
display: flex;
flex-wrap: wrap;
margin: 0 calc(var(--gutter) * -1px) ;
}
Flex defaults to 100% width, same as display: block. The negative margins works kind of like calc(100% + 20px) in addition to margin-left: -10px. Just neater. They're crucial to helps us offset the gutters coming from the columns.
We'll make a wildcard selector for our necessary helper class. On its own it doesn't really do much.
[class*="u-width"]{
padding-right: calc(var(--gutter) * 1px);
padding-left: calc(var(--gutter) * 1px);
flex-basis: calc((100% / var(--columns)) * var(--width));
}
This selector will kinda work as a function for the most part. Padding for gutters and flex-basis for width. The interesting part here is --width. Because of this variable we can set it on any element that matches our wildcard selector. An example:
<div class="u-width sidebar"> ... </div>
If we needed sidebar to be 2 columns wide we can do it simply by:
.sidebar{ --width: 2; }
.content { --width: 4; }
This works because variables in CSS are inherited and can be used as a scope. In other words, we just passed the --width to the u-width selector and calc takes care of the rest. Boom. Mic dropped. 14 lines of future vanilla CSS.
In addtion, you could extend this to be more like any other stand alone grid, but still with a lot less markup.
Here we've got a few elements with classes that define their width. I've used
<div class="u-width m--4 l--4"> ... </div>
, but it's really up to you. This is how they're setup:
.m--2{ --width: 2; }
.m--4{ --width: 4; }
.m--6{ --width: 6; }
.l--2{ --width: 2; }
.l--4{ --width: 4; }
.l--6{ --width: 6; }
/* media query are implied */
And that's it really.