Development Blog 7th May 2020

Generate max-width classes from Bootstrap's breakpoints using a Sass loop

I've never used loops in Sass before but I wanted to generate CSS classes that would set the max-width of an element based on Bootstrap's Grid Breakpoints. I use classes like these all the time for limiting the width of a form, but I usually code up some vanilla CSS for each width as I need it.

I googled 'How to write a Sass loop' and I came up with the code below.

scss
// Add mw-sm, mw-md classes and so on 
@each $name, $value in $container-max-widths {   
  .mw-#{$name} {     
    max-width: $value;   
  } 
}

I used $container-max-widths instead of $grid-breakpoints to compensate for container padding.

These classes may or may not be very useful, but it's good to know that you can do loops in CSS.