Brandon Durham
Brandon Durham

Reputation: 7707

SASS conditional variables?

I have a set of variables I'd like to set with conditions. Modernizr is handling the detection of touch-enabled devices for me, adding a .touch or .no-touch class to the HTML tag accordingly. I've got a global _settings.scss file that's just full of variables. A number of them are for layout and sizing, and I'd like to have many of those behave differently depending on the presence of the .touch and .no-touch classes on the HTML tag.

What are my options here?

Upvotes: 0

Views: 1263

Answers (1)

FranzHeidl
FranzHeidl

Reputation: 56

Not sure if setting variables by conditions that are compilation time independent (like your scoping classes on the body) is the right/most sensible way to go – You already know that you're going to need different values for some variable depending on a scoping body class, and these values don't seem dependent from any calculations or conditions that are known during compilation.

What I'd suggest (and do in a current project) is to use different variables for both like $my-var-touch and $my-var-no-touch (or $my-var--no-touch – yes, I'd even BEM-ify variables :) in your _settings.scss; and then do the relevant declarations/calculations in the scope of the actual selector:

.touch {
  .my-class {
    width: $my-var-touch;
  }
}

.no-touch {
  .my-class {
    width: $my-var--no-touch;
  }
}

The correct answer for your use case of course depends on what you're actually trying to do, how your import chain is set up, how far you go in terms of cacluations, etc., but I have found the approach I just roughly outlined to help me a lot oin terms of maintainability and readable, semantic scss code.

Upvotes: 2

Related Questions