New! Unlimited audio, video & web asset downloads! Unlimited audio, video & web assets! From $16.50/m
Advertisement
  1. Web Design
  2. Sass
Webdesign

Sass to CSS: How to Preserve Whitespace on Compile

by
Difficulty:IntermediateLength:ShortLanguages:

Ever wanted to keep the visual structure of your Sass files, when you compile to CSS, without losing any of the whitespace? In this quick tip I’m going to show you how!

Watch Quick Tip

 

This quick tip is for those of you who need to compile Sass to an “expanded” form. If you compile to “compressed” or “minified” then the whole question of there being whitespace is irrelevant.

The Problem

Imagine you have several Sass partials which are formatted like this, including the empty line breaks at the bottom:

Compiling them under normal circumstances would give you something like:

But let’s say you actually want the following:

The Solution

We’re going to solve things by using a Grunt plugin called grunt-replace. For details on how to get up and running with Grunt, take a look at the following resources:

We load grunt-replace, along with some other dependencies, in our package.json file as shown in the following snippet:

Then, in our grunt.js file we have to implement the task:

Match

We apply the replace task after we’ve compiled our Sass file (check out the source files for more details).

Notice the patterns option, which shows the following:

This instructs Grunt to go through the compiled file, find instances of /**/ and replace them each with an empty string. Now all we need to do is go through our Sass partials, place these /**/ comments wherever we actually want whitespace, and let Grunt do the rest:

Conclusion

Grunt-replace is a really useful task for finding common strings and replacing them with something else, whenever your run Grunt. In this case it’s the perfect tool to prevent whitespace from being stripped out of our compiled Sass. What else would you use it for?

Useful Resources

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.