Skip to content

Instantly share code, notes, and snippets.

@timotheemoulin
Last active November 26, 2020 21:54
Show Gist options
  • Save timotheemoulin/da51d68313a6973056eefb806d2bdd39 to your computer and use it in GitHub Desktop.
Save timotheemoulin/da51d68313a6973056eefb806d2bdd39 to your computer and use it in GitHub Desktop.
Render a flex view with unified gutter between elements
/**
* Use this mixin to generate a grid layout with flexbox.
* @param $gutter: the distance between two elements.
* @param $elementsPerLine: the number of elements on every row.
* @param $children: the children selector. Default value every children directly inside the wrapper.
* @param $elementsPerLineSmall: the number of elements on every row on smaller screens.
*/
@mixin display-flex-with-gutter($gutter, $elementsPerLine, $children: '*', $elementsPerLineSmall: 0) {
display: flex;
flex-wrap: wrap;
& > #{$children} {
width: 100%;
flex-grow: 0;
margin: 0 0 $gutter;
@if $elementsPerLineSmall == 0 {
@media (min-width: 768px) {
@include _display-flex-with-gutter($gutter, $elementsPerLine, $children);
}
} @else {
@media (min-width: 768px) and (max-width: 1439px) {
@include _display-flex-with-gutter($gutter, $elementsPerLineSmall, $children);
}
@media (min-width: 1440px) {
@include _display-flex-with-gutter($gutter, $elementsPerLine, $children);
}
}
}
}
/**
* Internal method called by the main mixin.
*/
@mixin _display-flex-with-gutter($gutter, $elementsPerLine, $children) {
max-width: calc((100% - (#{$gutter} * 2 * #{$elementsPerLine - 1})) / #{$elementsPerLine} - 1px);
margin: 0 $gutter #{$gutter * 2};
&:nth-child(#{$elementsPerLine}n+1) {
margin-left: 0;
}
&:nth-child(#{$elementsPerLine}n) {
margin-right: 0;
}
&:nth-last-child(-n+#{$elementsPerLine}) {
margin-bottom: 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment