Creating lists of CSS selectors with SASS

Jun 21st, 2016 in  by Michael Cho

I like to use CSS selectors like .margin-top-10, .padding-right-20, etc to quickly style a new page. Here's how I create them in SASS.

If you are not already using SASS in your projects, you should seriously consider doing so. It makes it *much* easier to keep your CSS workable.

Usually I end up with a whole bunch of helper CSS classes which add a variety of padding or margin attributes to any page element. My CSS file quickly ends up with a section looking like this:

// CSS file
.margin-10 { margin: 10px; }
.margin-20 { margin: 20px; }
.margin-30 { margin: 30px; }
.margin-40 { margin: 40px; }
.margin-50 { margin: 50px; }

.padding-10 { padding: 10px; }
.padding-20 { padding: 20px; }
.padding-30 { padding: 30px; }
.padding-40 { padding: 40px; }
.padding-50 { padding: 50px; }

That's not including all similar selectors such as .margin-left-*, .margin-top-*, .margin-bottom-*, and so on. 

Here's how to generate these classes very quickly using SASS:

// SCSS file
$gap-list: (

@each $value in $gap-list {
    $gap: nth($value, 1);

    .padding-#{$gap}          { padding: #{$gap}px; }
    .padding-bottom-#{$gap}   { padding-bottom: #{$gap}px; }
    .padding-top-#{$gap}      { padding-top: #{$gap}px; }
    .padding-left-#{$gap}     { padding-left: #{$gap}px; }
    .padding-right-#{$gap}    { padding-right: #{$gap}px; }

    .margin-#{$gap}          { margin: #{$gap}px; }
    .margin-bottom-#{$gap}   { margin-bottom: #{$gap}px; }
    .margin-top-#{$gap}      { margin-top: #{$gap}px; }
    .margin-left-#{$gap}     { margin-left: #{$gap}px; }
    .margin-right-#{$gap}    { margin-right: #{$gap}px; }

Be careful with the semi-colons at the end of $gap-list - it is the semi-colon which makes it a list, not the brackets!

Other articles you may like

Bash script to relink alembic migrations
Jun 12th, 2017
Running Metabase locally as a service
May 29th, 2017
Debugging mobile apps with Charles proxy
Aug 15th, 2016