Advanced SCSS

Or, 16 cool things you may not have known your stylesheets could do. I'd rather have kept it to a nice round number like 10, but they just kept coming. Sorry.

I've been using SCSS/SASS for most of my styling work since 2009, and I'm a huge fan of Compass (by the great @chriseppstein). It really helped many of us through the darkest cross-browser crap. Even though browsers are increasingly playing nice with CSS, another problem has become very topical: managing the complexity in stylesheets as our in-browser apps get larger and larger. SCSS is an indispensable tool for dealing with this.

This isn't an introduction to the language by a long shot; many things probably won't make sense unless you have some SCSS under your belt already. That said, if you're not yet comfy with the basics, check out the awesome CSS extensions you've always wished you had:

The tips are vaguely ordered from basic to more advanced. If you're immediately bored, feel free to skip ahead to the deep end of the pool. Also, if you have any questions, comments or corrections, leave a comment below, or fork this gist and let me know!

This can be very useful when you have a deep nesting of rules, and you want to effect a change to the styling of an element based on a selector match much closer to the DOM root. Client capability flags such as the Modernizrno-touch class are often applied this way to the <body> element. This way you don't have to back out of your nesting just to be able to change your <p> styling based on a class on the <body>.

2. Variable expansion in selectors

Variables can be expanded in selectors, too:

$alertClass: "error";
p.message-#{$alertClass} {
color: red;
}

/* compiled CSS */p.message-error {
color: red;
}

...or almost anywhere else for that matter, like in media queries or CSS comments:

The media query example is particularly useful if the $breakpoint variable is defined in a settings partial somewhere (say, _settings.scss), so the breakpoints of the entire application are configurable from one file.

3. Variable defaults

If your SCSS module can be configured using globals (which tends to be the SCSS way), you can declare them with a default value:

But you can then optionally override the module defaults before its inclusion:

$message-color: black;
@import 'my-module';

/* compiled CSS */p.message {
color: black;
}

That is, an assignment with a !default will only take effect if such a variable didn't have a value before (in contrast to the standard assignment, which will always overwrite a possible previous value).

This is how many SCSS modules (including most that ship with Compass) are configured.

...and much more. Keep in mind, though, that if you need them in your daily styling work you're probably overdoing it a bit. Instead, the added complexity is usually justified when building configurable SCSS modules and such.

5. The list data type

As we saw in the previous example, @each can iterate over a list. Lists are in fact a fundamental part of the SCSS language, but a quick demonstration of their usefulness might be configuring some generated styling:

That is, lists can be separated by both spaces and commas, and alternation between the two notations produces nested lists.

6. Defining custom functions

Mixins are a well-known part of the language, but SCSS also allows you to define custom functions. Contrary to what one might expect, this can also be done in pure SCSS, instead of extending SCSS in Ruby:

Custom functions are most useful in avoiding some repeated computation in an expression. It also implicitly documents that computation by giving it a name: the above example, while contrived, is still more understandable than just having arbitrary color arithmetic in the style block. SCSS ships with a ton of useful built-in functions, and Compass adds even more, so do first check whether there's a built-in equivalent before implementing your own.

7. Argument defaults

Mixins and functions support default values for arguments; the last zero-to-N arguments can be made optional by providing them with a default value:

Without being able to name arguments call-time, you'd have to specify $topPadding and $rightPadding first. Now, you can instead override only the argument you want, leaving the rest to their default values.

Note, however, that in cases where a lot of the arguments are just for overriding specific CSS properties (such as top-padding, bottom-padding and so on), the "content block overrides" -pattern is likely a better fit (see below).

9. Variable arguments for functions/mixins

Var-args work much the same way as in other languages that support the feature; any extra arguments to a function/mixin call are wrapped into a list and assigned to the argument having a ... suffix:

The above helper could be used to set up colors for your font icons, Font Awesome for example, without having to repeat yourself. The helper works by passing in a variable number of arguments (after the first, required one). Each of those arguments is expected to be a tuple of two items (again in JavaScript notation, for example [ "save", "green" ]).

In fact, the ... syntax also works during call-time, where it expands a list into separate arguments, to be fed into the target mixin:

This is a very powerful language feature for framework authors, as it allows you to pass arbitrary blocks of styling around, which you can choose to wrap in specific selectors, repeat in loops, make conditional with @if, etc. You can mix standard and content block arguments, too:

Calling this mixin using keyword arguments (see above) is quite convenient, because if the defaults are fine, no extra arguments need be provided. If they're not, you only need to specify the arguments you want to override:

@includemessage("subtle", $margin: 5px);

But this requires you to list all overridable properties in the mixin signature. However, content block arguments allow arbitrary overrides without the argument jungle:

Here, we allow the good-ole CSS cascade to effect the property override (the latter margin overrides the former one). Also, we're not limited to overriding the properties the author of the mixin thought of. In fact, this allows passing in nested blocks as well:

This pattern can be useful in any library code that outputs nontrivial styling with generated selectors, since it allows the user a customization point beyond what the library author foresaw. Note, though, that in simple cases (where no selectors are emitted within the mixin) it's rather unnecessary, as any overrides can be made just using the standard CSS cascade.

12. Media query bubbling

@media blocks do not need to be declared at the root level of the stylesheet:

Notice how the compiler "bubbles up" the @media block to the root level (since regular CSS doesn't support selector nesting), and within it, outputs all styling that was encountered within the @media block in the SCSS source.

This is very useful as it allows you to make media-specific tweaks almost anywhere in your styling, right where they're relevant, instead of collecting all those tweaks to the end of the stylesheet, and hoping that their selectors will stay in sync with the ones they're overriding (they won't).

13. Media query nesting

The aforementioned bubbling mechanism also takes nesting into account, and combines all applicable queries with the and operator:

14. Extending selectors

SCSS allows extending selectors, by copying and combining selectors in the CSS output. Interestingly, while the mechanism is (obviously) very different, the semantics of @extend are quite analogous to traditional object-oriented programming languages (such as Java & whatnot):

That is, .cat has all the properties of its "parent class" .animal, plus any specific ones it adds or overrides. Whereas in normal CSS you would have to reference both the extending class and the parent class (e.g. <div class="animal cat">), now you can just name the exact class you want (<div class="cat">). What it does (or doesn't) inherit from depends on the definition of .cat, and can later change without touching the markup.

Classical inheritance, right? Overriding properties in the "child class" works due to the style cascade in the browser: styling for the same selector that comes later in the file always wins over the styling that came before it. Perhaps a bit unintuitively, this actually works out fine even if the combined selectors have differing specificity (think .class extending an #id). Extending selectors may often be preferable to using mixins to achieve the same effect:

Notice how only the last property (color) is different, the rest is the same. As we define more types of animals, the amount of repeated style properties in the CSS output keeps growing. This is in contrast to how selector extension would solve the same problem:

Finally, selector extension allows for integrations into 3rd party CSS libraries, that need not be specifically designed for extension, or even be written in SCSS. Twitter Bootstrap, for example, includes nice styling for buttons with .btn, but doesn't apply it to <button> elements by default. In our quest to reduce unnecessary CSS classes, we can fix this simply with:

This will add the button selector into the Bootstrap source wherever .btn is defined.

The extension mechanism is surprisingly clever even with more complex selectors, and allows chaining extends (think .cat extends .feline extends .animal), but with great power comes great responsibility: overly neat tricks with @extend may be hard to reason about when debugging styles. Use responsibly.

15. Placeholder selectors

Because in the above example(s) the .animal base class isn't used anywhere directly (only through its child classes), we might just as well get rid of it in the CSS output. SCSS allows this with placeholder selectors. Whereas .foo signifies a class, and #foo an ID, %foo is considered a placeholder, and gets special treatment by the compiler: its styles are never output on their own, only through extension.

Because %animal was just a placeholder selector, it's disappeared from the output. More importantly, if you never define a selector that extends %animal, its styles (background: gray; and so on) are completely omitted from the output. This can be very useful for SCSS framework authors, as you can offer any number of base classes for opt-in extension, but only the ones actually used are output into the resulting CSS.

Placeholder selectors can actually do even more than this, namely expanding the %placeholder part into a more complex selector during @extend, but personally I've never had to use this feature. The interested reader can check out the docs on the subject.

16. Selector multiple inheritance

A selector can actually inherit from several other selectors - that is, SCSS supports multiple inheritance. For each @extend, the current selector is appended to the selector being extended. When combined with placeholder selectors, this allows powerful abstractions for styling framework authors. This is perhaps best explained through an example:

Self-documentation: Instead of writing out loads of anonymous style properties, the author instead lists the "traits" of the UI component he is designing. The names of the traits can be as long & descriptive as needed (they won't appear in the CSS output).

Naming isolation: The application can use whichever naming conventions and semantics in the HTML, while the framework naming conventions stay internal to the SCSS source. In the above example, the framework adopts a common prefix %mfw (for "my framework", or whatever) to avoid naming collisions with other SCSS libraries.

Reduced repetition: The #join-button could use the border-radius() and box-shadow() helpers directly to achieve the same stylistic effect. But for each additional component that does so, the box-shadow() helper would output the exact same lines of CSS, with all the vendor prefixes and whatnot. Extending %mfw-slightly-shadowed, however, would simply append the selector to the list of other selectors that should receive shadowing.

Opt-in: If a specific "trait" is never used to describe a UI component, its styles are never output. That is, if you just use 1% of the features of a bloated style framework, your CSS payload will only contain that 1%. Contrast this to the de-facto way of just including an entire Bootstrap or jQuery, because the site uses 1 or 2 features from each.

Potential downsides with this approach should be kept in mind:

Debuggability: Without properly configured source maps for SCSS, it may be harder to figure out how some styling ended up affecting a specific element (keeping in mind the above point about self-documentation no longer applies in the compiled CSS).

Arguments: This technique won't replace mixins when computation is required based on some arguments. While there can be several versions of each "trait" (think %mfw-slightly-shadowed vs %mfw-heavily-shadowed), they'll always be completely static in content.

This comment has been minimized.

This comment has been minimized.

edited

Hi Guy, in your 1st example you show us the familiar way of using & as a prefix and then you show us a way how to use it as a 'suffix' which is what I think you meant to say? Anyways... thanks for this as this is good to know.

I have a question perhaps you might answer or one of your colleagues. Is there a way for SASS to generate CSS that doesn't get placed in the css file, but instead get placed in the html header for 'above the fold content'? Just asking as I am facing this issue.

This comment has been minimized.

This comment has been minimized.

edited

Nice write up! One thing that I've really enjoyed is Sass maps. I've been teaching a friend to program who has no experience, and Sass provides some great options to segue from markup to programming. For example, using maps to create a config object of a component's properties:

$config: ( color: '#fff', border: '1px solid #000', z-index: 10 )

You can then use the map-get function to retrieve the values, like this:map-get($config, color)

This comment has been minimized.

This comment has been minimized.

I've a question: I know that it's possible to add custom attributes to html page of ionic project (like attribute item-one) to manage a component in the scss, recalling that attribute with square bracket ([item-one]). Someone can link tutorial to understand how to do that in the better way???

// tablet
// Both the portrait and landscape width of the tablet
// Larger than a landscape mobile but less than or equal to a landscape tablet@mixin tablet-only {@media only screen and (min-width: $mobile-large + 1) and (max-width: $tablet) {@content;
}
}

// Everything up to and including the portrait width of the phone
// Since it's the smallest query it doesn't need a min@mixin mobile-portrait-only {@media only screen and (max-width: $mobile-portrait) {@content;
}
}

// Everything up to and including the mobile portrait@mixin mobile-portrait-and-below {@media only screen and (max-width: $mobile-portrait) {@content;
}
}

// Everything larger than mobile landscape up until the portrait width of the tablet@mixin tablet-portrait-only {@media only screen and (min-width: $mobile-landscape + 1) and (max-width: $tablet-portrait) {@content;
}
}

// Everything below and including the portrait width of the tablet@mixin tablet-portrait-and-below {@media only screen and (max-width: $tablet-portrait) {@content;
}
}

// Everything above and including the portrait width of the tablet@mixin tablet-portrait-and-up {@media only screen and (min-width: $mobile-landscape + 1) {@content;
}
}

// Larger than portrait but less than or equal to the landscape width@mixin tablet-landscape-only {@media only screen and (min-width: $tablet-portrait + 1) and (max-width: $tablet-landscape) {@content;
}
}

// Up to and including the tablet landscape@mixin tablet-landscape-and-below {@media only screen and (max-width: $tablet-landscape) {@content;
}
}

This comment has been minimized.

This comment has been minimized.

Any of you Sass experts out there care to answer a question I've been struggling to find resources for?

I have an app with a bunch of sass, and some of my sass comes from a UI kit. (sass/codebase)
My app also has custom hand written sass. (sass/base)

There are some media queries handled by the UI kit that are actually causing more bad than good in my particular situation so I need to find a way to write sass in sass/base that ignores/overrides/disables two media queries in sass/codebase. Is there a way to do this? I've looked everywhere online and unfortunately while there's a lot of resources for learning about media queries, there's not a lot of resources out there for how to cancel media queries without actually removing them from the code. Any help would be spectacular