3
votes

So I ran into something weird.. I'm using the 7-1 pattern for my CSS needs. For those unfamiliar you can read about it here: https://sass-guidelin.es/

I have a _variables.scss file where I have some css variables declared. My question is that I can access these variables in other .scss files without using the import statement in that particular file. Can anyone explain why?

Edit: My guess is that I have a main.scss file that SCSS is watching which is importing all the other files. By the time the CSS is attempting to be transpiled the variables are available to it in the other files?

1

1 Answers

1
votes

I'm gonna assume you've got one master import file, with something like:

@import 'variables'
@import 'base'
@import 'some_component'
@import 'some_other_component'

The reason your variables are available to your other stylesheets is that the imports cascade. So, as soon as you import variables, everything imported after is in the same scope as those variables (as they've been imported).

This can be a blessing and a curse, as any variables you define outside of block scope in any of your other stylesheets will also become globally available to all stylesheets imported after that one.

Because of this, it's generally considered best practice to import all variables that are to be global at the very top of your main import stylesheet, and then block-scope any local variables that you don't want to expose globally, like so:

.SomeComponent {
  $height: 100px; // this is only accessible from within this block, and children of this block;

  .SomeComponent-child {
    height: $height;
  }
}

Conversely, a variable defined in _variables.scss will be available everywhere, so you could also do:

.SomeComponent {
  $height: $global-height; // `$global-height` defined in `_variables.scss` 

  .SomeComponent-child {
    height: $height;
  }
}