Jump Start Sass by Hugo Giraudel Miriam Suzanne

Jump Start Sass by Hugo Giraudel Miriam Suzanne

Author:Hugo Giraudel, Miriam Suzanne [Giraudel, Hugo]
Language: eng
Format: epub, mobi, pdf
ISBN: 9780994182678
Publisher: SitePoint Pty. Ltd.
Published: 2016-08-16T04:00:00+00:00


Variable Scoping

We often put selector nesting and variable scoping together, and for good reason. Because of the way variables work in Sass, when defining variables inside a rule set, all the nested rule sets will have access to them. Consider our previous example:

.container { margin: 0 auto; max-width: 42em; padding: 0 1em; p { text-indent: 1em; } }

Let’s assume we want the horizontal padding of the container and the text indentation of paragraphs to be a shared value (here, 1em). A variable is a smart and simple way to do this. Now, depending on where we declare it, its access will be restricted to some selectors and not others.

In the following code snippet, the $rhythm variable is defined at the root level, which means it’s available for the entire stylesheet. This includes other (imported / importing) files. That might be what you’re after. Or not:

$rhythm: 1em; .container { margin: 0 auto; max-width: 42em; padding: 0 $rhythm; p { text-indent: $rhythm; } }

What if we want to restrict $rhythm to the .container selector? We have seen how to do this in the chapter dedicated to variables: we move the variable declaration two lines down:

.container { $rhythm: 1em; margin: 0 auto; max-width: 42em; padding: 0 $rhythm; p { text-indent: $rhythm; } }

What’s nice about this is that the p rule set is still able to access $rhythm because it’s been defined in a parent scope. We get the best of both worlds: our variable is scoped to a specific context (not global), and we can use it to share a value between several rule sets. Win-win.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.