SASS Mixin For Fluid Grids Chris Poteet, February 21, 2014August 27, 2023 I started my foray into SASS trying to get it to just work in SharePoint, and I proved that it can be done. Now I want to continue to grow in my understanding of the language. I decided to look at grids because SASS seems particularly efficient for defining grids. Now, SASS grid frameworks are a dime a dozen, and there are some really good ones like Bourbon’s Neat and Susy. I just wanted something dead simple for me to define these, and so what follows is my first attempt at a more robust SASS mixin. I am publishing this because I want feedback on how to be a better SASS developer. You’ll notice the general approach is similar to many of the SASS grid libraries. So here’s the code that I will walk through: $numCol: 4 !default; $gutterWidth: 1em !default; @mixin grid($col, $lastChild: false) { // Calculate column width $colWidth: percentage($col / $numCol); // Check if last child @if $lastChild { width: $colWidth; margin-right: 0; } @else { // Find width = gutter width: calc(#{$colWidth} - #{$gutterWidth}); margin-right: $gutterWidth; } display: inline-block; } .sidebar { @include grid(1); } .main { @include grid(3, $lastChild: true); } First we have two variables: numCol and gutterWidth. For numCol you just have to think how many columns do you actually want in your grid. In my case, I’ve chosen 4. The second variable is the gutter width. This can be any value that you want on the right side of the columns. Then you call the mixin with grid(). You pass in how many columns you want this to span of the total number you defined in numCol. So for sidebar I passed in 1, so I want the sidebar to be 1/4 of the total width. You can see also when I called the mixin on the main div I passed in also $lastChild: true. The mixin has conditional logic to remove the gutter on the final column, and this boolean turns it on/off. There are two things to note here. First, I’m using inline-block for the divs. I could use float, but man do I ever hate floating layouts. So you’ll need to be careful for that weird inline-block white space issue. Second, I’m using the CSS calc() function to handle the addition of the gutter. This means you need to watch out for browser support and use appropriate prefixes. You want to particularly watch out for IE 8 and below and also Opera Mobile (see browser support). Here is the CodePen example with some media queries to show it working responsively (open it on CodePen to see it working since the demo below is small). See the Pen SCSS Grid Mixin by Chris Poteet (@cpoteet) on CodePen.0 So that’s it for my first attempt at a little more of a complex mixin. I’m still new at this, but I’m excited for all the possibilities SASS has to offer. Related Posts Development User Interface fluidgridmixinresponsiverwdsassscss
Yes it is very cool. I’ve created my mixins to manage the chrome of a webpart, not so difficult but it can be painful to mix SP and sass.. :) Reply