Breaking out of a Sass mixin - sass

Is it possible to break out/return early of a Sass mixin? I'd like to do something like this:
#mixin foo($bar: false) {
#if $bar {
// return early without applying any of the styles below
}
color: red;
}
Edit: Please keep in mind that this example is the simplest thing I could come up with that illustrates my problem. In the real world, my code is much more complex and the use case for this is clear.

Sass doesn't really have the concept of "break", but an #if/#else will get you pretty close:
#mixin foo($bar: false) {
#if $bar {
color: green;
}
#else {
color: red;
}
}
From the Lead Sass developer at https://github.com/nex3/sass/issues/378:
The issue is that the more seldom-used control structures exist in
Sass, the harder it is for something with only passing familiarity
with the language to read stylesheets that use those control
structures. That's why it started out with the bare minimum set of
structures needed to do anything: because in many cases it makes sense
to skew towards a smaller surface area of the language rather than
optimal semantics for writing complex code.

I still thinking that #if/#else statements is the easiest and best solution to deal with your problem in Sass but I've created two different breakout mixins to help you and as a challenge:
Play with this mixin first
Breakout mixin without #includes (link)
#include breakout($styles)
$style should be a list of styles separated by spaces, here are the allowed values:
Styles
Common CSS styles separated by spaces and without colon or semicolons, lists of values should be wrapped by brackets:
#include breakout(
color blue // <property> <value>
width (100 * 20px) // <property> <operation with values>
border (1px solid #fff) // <property> <list of values>
box-shadow (0 0 10px 4px #0000FF , 0 0 20px 30px #008000) // <property> <nested list of values>
)
Breaks
Breaks are styles that are compiled if its condition is true, also when the condition is true the mixin ends without returns all styles after the break value
$foo: true;
#include breakout(
break (false color red) // break (<condition> <property> <value>
break ((3 < 2) border (1px solid #fff)) // breaks also support list and nested lists
break ($foo width 10px) // This breaks is compiled because condition is true
color blue // This style isn't compiled because the $foo break ends the mixin
)
Note that the order of the mixin argument list is important because it determines the compiled and not compiled styles if a break condition is true
Breakout mixin with #includes (link)
This mixin is similar to the above but it introduces mixin values for $styles, break-mixin mixin and #content into the breakout mixin to allow use of #includes.
Mixins
If you want to use other mixins into breakout mixin you need to add some code into $styles and add each mixin into a break-mixin mixin.
#include breakout(
mixin foo // mixin <name of the mixin declared into break-mixin arguments>
mixin bar // mixin name should match break-mixin argument
mixin foobar
) {
#include break-mixin(foo) { // Here your mixin or mixins for mixin foo }
#include break-mixin(bar) { #include mixin1; #include mixin2; #include mixin3}
#include break-mixin(foobar) { #include foobar}
}
Mixin breaks
Now you can also use mixin into breaks. Here the order is still important:
$foo: true
#include breakout(
mixin foobar
mixin bar
break ($foo mixin foo) // This breaks is compiled because condition is true
color blue // This style isn't compiled because the $foo break ends the mixin
) {
#include break-mixin(foo) { // Here your mixin or mixins for mixin foo }
#include break-mixin(bar) { #include mixin1; #include mixin2; #include mixin3}
#include break-mixin(foobar) { #include foobar}
}
So for your specific case copy the Breakout mixin without #includes (link) to your scss file or use it as a partial and then add this to your code;
#include breakout(
break ($bar property value) // The break out statement
color red // If $bar != false this will be compiled if not it won't
);

I'm surprised that the #error statement has not been mentioned yet. According to the documentation (emphasis mine):
When writing mixins and functions that take arguments, you usually want to ensure that those arguments have the types and formats your API expects. If they aren't, the user needs to be notified and your mixin/function needs to stop running.
That said, #error may not be suitable for every situation, because it will stop the Sass compilation completely. This makes it unfit for mixins where breaking out is an expected end intended scenario.
Example from the Sass documentation:
#mixin reflexive-position($property, $value) {
#if $property != left and $property != right {
#error "Property #{$property} must be either left or right.";
}
$left-value: if($property == right, initial, $value);
$right-value: if($property == right, $value, initial);
left: $left-value;
right: $right-value;
[dir=rtl] & {
left: $right-value;
right: $left-value;
}
}
.sidebar {
#include reflexive-position(top, 12px);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Error: Property top must be either left or right.
}

Related

How to make an alias for a Sass mixin with multiple arguments?

Since I couldn't find a Question for this specific problem, I will post the solution I came up with.
I want to create an alias for a Sass mixin which has multiple arguments (partially optional ones).
#mixin box(
$width,
$height,
$background-color: transparent
) {
width: $width;
height: $height;
background-color: $background-color;
}
For this mixin I want to create an alias which just takes all arguments given and passes them through to the original mixin:
#mixin box_alias(
$width,
$height,
$background-color: transparent
) {
#include box( $width, $height, $background-color );
}
It feels very redundant to keep listing all arguments again, this totally works agains the DRY principle. So I am looking for a more elegant solution.
In Sass you have the possibility to allow a mixin (or function) to have an arbitrary number of arguments. To do this you make the last argument an argument list by appending three dots (...) to its definition. If there is only one argument and it ends with the three dots, then the resulting arument list will contain all arguments passed to the mixin. This works very similar to the spread operator in ES2015.
The resulting argument can be passed on to original mixin, adding the three dots again to unfold them as separate arguments for the call:
#mixin box_alias($arguments...) {
#include box($arguments...);
}
This works well for positional and keyword arguments (even in combination) and also for optional arguments.

Shortening code by using a variable for including mixin

I'd like to know if there is a way to include a mixin (compass or my own) by a value of a specific variable.
Currently I have the following mixin (which works)
#mixin aligned-top-bottom-border($size, $side){
#if $side == "left"{
#include border-top-left-radius($size);
#include border-bottom-left-radius($size);
}
#else{
#include border-top-right-radius($size);
#include border-bottom-right-radius($size);
}
}
I'd like to turn it to something like the code below (or any other alternative that is shorter and more readable)
#mixin aligned-top-bottom-border($size, $side){
#include border-top-#{side}left-radius($size);
#include border-bottom-#{side}-radius($size);
}
I'm using Sass 3.4.5 (Selective Steve)
Sass documentation has this to say about interpolation:
You can also use SassScript variables in selectors and property names
using #{} interpolation syntax
Nothing about using them in mixins or functions. But there is nothing stopping you from adding your own vendor loop to the mixin instead of using the compass mixin. Like this:
#mixin aligned-top-bottom-border($size, $side){
#each $vendor in ('-webkit-', '-moz-', '-ms-', '-o-', ''){
#{$vendor}border-top-#{$side}-radius: $size;
#{$vendor}border-bottom-#{$side}-radius: $size;
}
}
It gets a bit DRYer but a lot bigger in final output. But it possible.

Check if SASS parent selector exists. Is it possible

I have a question. So in a mixing I am making a reference to the parent selector "&". This works as long as the mixin is not nested. Is there a way to to detect if the mixing is being used in a non nested scenario, or to check if "&" is null?
This works when the mixin call is not nested
=myresponsiveMixin($media)
#if $media == small {
#media only screen and (max-width: $break-small)
#content
#else if $media == medium
#media only screen and (min-width: $break-small + 1) and (max-width: $break-large - 1)
#content
This works great when the mixin call is nested, but will not resolve '&' when not nested
=myresponsiveMixin($media)
#if $media == small {
#media only screen and (max-width: $break-small)
.classInHTMLToAllowMediaQueries &
#content
#else if $media == medium
#media only screen and (min-width: $break-small + 1) and (max-width: $break-large - 1)
.classInHTMLToAllowMediaQueries &
#content
So the question is, if there is a way to be able to check the value of parent selector "&", so I can cover all bases in a single mixin?
#mixin does-parent-exist {
#if & {
.exists & {
color: red;
}
} #else {
.doesnt-exist {
color: red;
}
}
}
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-script
You're trying a wrong solution to solve your issue.
Have a look at how this problem is addressed in powerful SASS frameworks. Let's take Susy by Eric Meyer as a great example.
Let's imagine you've got the following HTML:
<div class="container">
<div class="parent">
<div class="child">
Bla bla
</div>
</div>
</div>
When you call a mixin for the first time, you're doing it simply (the code is in the indented .sass syntax):
$total-columns: 8 // Declaring a varible that will be used by the mixin
.parent
+span-columns(4) // Span four of eight columns
But when you call that for a child element, the proportions would be crooked, because the parent is already proportioned:
.child
+span-columns(2) // This will fail. You want 2 of 8 columns,
// but due to nesting the math is crooked.
// It will be "2 of (4 of 8)".
To address the issue, you provide an optional argument: a context that is used to do the math:
.child
+span-columns(2, 4) // Now the mixin will take 2 parts of 4
// instead of 2 parts of four
The source code for this mixin is available on GitHub.
In short, it creates an optional argument like this (the code is in the CSS-like .scss syntax):
#mixin span-columns(
$columns,
$context: $total-columns
//...
) {
//...
width: columns($cols, $context /*...*/);
//...
}
See how $context has a default value? Thanks to the default value this argument can be omitted. In other words, $context is an optional argument.
When calling this mixin, if $context is not provided (e. g. span-columns(2)), then it is set equal to $total-columns. The $total-columns variable should be set prior to calling the mixin for the first time (see my example above).
Then the two arguments are used to calculate the width.
UPD 2013-03-30
I am not trying to figure out things in regards to columns... I have modifier my question to make it clearer.
First of all, my recommendation concerns not only grid columns. It's a universal technique you can adopt.
Secondly, now i see that you're trying to nest media queries.
Well, some media queries of different type can be combined in CSS3: e. g. print and width. But you can't put a min-width: 601px inside max-width: 600px, this just won't work!
There's an extensive answer here on StackOverflow describing why you should not nest media queries of the same type: https://stackoverflow.com/a/11747166/901944
Thirdly, you're trying to invent the wheel. There's already a fantastic mixin for crunching media queries: Respond To by Snugug. It's super easy to use and very effective.
Fourthly, the XY thing. Instead of asking about your crooked mixin, please describe the problem that you're trying to solve with it! Show us the actual HTML and explain what behavior you would like to achieve.
We will show you that it can be solved with a simple, elegant, semantic solution that does not require SASS hacking.

Using SASS Function on an existing Mixin?

I have an existing mixin which creates a background gradient:
#include bg_gradient($dark:#292446, $light:#3e395b, $highlight:#65617d);
I want to have a hover lighten it , I cannot seem to figure out how to hand that off to the function:
lighten(#include bg_gradient($dark:#292446, $light:#3e395b, $highlight:#65617d), 10%);
does not work , I have also tried rolling into into the end as you can do with other CSS attrs:
#include bg_gradient($dark:#292446, $light:#3e395b, $highlight:#65617d, lighten ($dark, 10%));
Also, tried assigning the mixin to a variable and passing it in as such:
lighten($gradient-value, 10%);
Mixins don't return a value, so you can't use functions on them. In your 2nd example, what you need is to be able to pass the function itself as an argument, which isn't currently possible. Your only option is this (assuming you wanted to apply the function to all 3 arguments):
#include bg_gradient($dark: lighten(#292446, 10%), $light: lighten(#3e395b, 10%), $highlight: lighten(#65617d, 10%));

unset compass single-text-shadow()

Is there a way to unset or remove the text-shadow effect of the compass function ?
e.g. i want to set the text shadow globally for all header elements and then eliminate it for certain cases.
h2 { #include single-text-shadow($blue, 1px, 1px, 0); }
As in CSS, simply declare none:
.specific h2 { #include single-text-shadow(none); }

Resources