Advanced Sass : online course

Dynamic %placeholders in Sass

Placeholders are a great tool to DRY your Sass by using @extend instead of mixins, while still keeping the CSS clean of unused code. A little known fact is that you can dynamically set the names of placeholders to extend, allowing you some crazy Sass architecture.

Play with this gist on SassMeister.

This snippet uses the $placeholder-name variable to create the %foo placeholder. It's the validation for us being able to dynamically create placeholders. By itself this doesn't have much use, but assume the following use case:

For a project you want to embed images in your CSS, by Base64 encoding them (e.g. because you don't want multiple HTTP-requests for fetching a bunch of small icons). The compiled CSS will look something like background: url(data:image/png;base64,R0lGODlhEAAQAMQA... for an embedded png file. What we don't want is to encode the same file multiple times, because we increase the file size of our compiled CSS by the source image size with every inclusion (plus ~30% in overhead from encoding to Base64). That's why @extend is great to use in combination with embedded media. Add some creative looping, and we end up with this:

PS: Normally I'd use Compass or another tool to automatically take care of the encoding, but in this example I added my own function that would wrap the call to this third-party tool. To keep things simple, it outputs a static string in the example.

Play with this gist on SassMeister.

To be able to add lots of icons I created an $icons map that holds a combination of user-friendly placeholder names and images. By using @each to loop through this list, casting key and value on the $icon and $filename variables, we can dynamically construct our placeholders. The "alert" icon is used twice, but appears in the compiled CSS just once. The "help" icon isn't used at all, and while it's readily available by using the %help placeholder, it doesn't pollute our CSS with any output as long as we're not actively using it.

I'm looking forward to your thoughts on this one. Please drop a comment below!

The above is part of the Advanced Sass online course, which helps you turn your Sass up to eleven. You can become a Sass expert too!