Skip to content

Instantly share code, notes, and snippets.

@romainl
Last active May 26, 2017 09:41
Show Gist options
  • Save romainl/7121596ac7284a1a5da1 to your computer and use it in GitHub Desktop.
Save romainl/7121596ac7284a1a5da1 to your computer and use it in GitHub Desktop.
Simplistic [S]CSS grid with minimal markup and accurate padding distribution.
<!-- grid -->
<div class="my-grid">
<!-- rows -->
<div>
<!-- cells -->
<div>content 1</div>
<div>content 2</div>
<div>content 3</div>
<div>content 4</div>
<div>content 5</div>
<div>content 6</div>
</div>
<div>
<!-- cells -->
<div>content 1</div>
<div>content 2</div>
<div>content 3</div>
<div>content 4</div>
<div>content 5</div>
<div>content 6</div>
</div>
</div>
// gutter distibution
@mixin gutters($col-max, $col-min, $gutter-width) {
width: #{100% / $col-min};
@if $col-min > 1 {
$i: 0;
@for $group from 0 to $col-max / $col-min {
@for $col from 1 through $col-min {
&:nth-child(#{$col + $i}) {
padding-left: $gutter-width * (($col - 1) / $col-min);
padding-right: $gutter-width * (($col-min - $col) / $col-min);
}
}
$i: $i + $col-min;
}
}
@else {
padding-left: 0;
padding-right: 0;
}
}
@mixin grid($actual-cols, $desired-cols, $gutter) {
// grid
width: 100%;
> * {
// row
width: 100%;
font-size: 0;
> * {
// cell
display: inline-block;
font-size: initial;
vertical-align: top;
box-sizing: border-box;
@include gutters($actual-cols, $desired-cols, $gutter);
}
}
}
.my-grid {
@media only screen and (min-width: 320px) and (max-width: 767px) {
@include grid(6, 1, 2rem)
}
@media only screen and (min-width: 768px) and (max-width: 1024px) {
@include grid(6, 3, 3rem)
}
@media only screen and (min-width: 1025px) {
@include grid(6, 6, 4rem)
}
> * > * {
margin: 0 0 2rem 0;
text-align: justify;
}
}
// JS implementation of the SCSS logic above
function setPadding(element, width) {
var columns = [].slice.call(element.children);
var rows = [];
var cur_col = 0;
while (cur_col < columns.length) {
var column = columns[cur_col];
if (column.offsetLeft === columns[0].offsetLeft) {
rows.push([column]);
} else {
rows[rows.length - 1].push(column);
}
cur_col++;
}
var cur_row = 0;
while (cur_row < rows.length) {
var row = rows[cur_row];
var i = 0;
while (i < row.length) {
row[i].style.paddingLeft = width * (i / row.length) + "rem";
row[i].style.paddingRight = width * ((row.length - (i + 1)) / row.length) + "rem";
i++;
}
cur_row++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment