Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

css - How to change sass import file when body class is changing

Is any way to change scss file with color variables when class in body is changing?

I mean when I have in html:

<body class="custom"> ... </body>

I want to load in style.scss

@import 'custom';

and when I have

<body class="dark-mode"> ... </body>  

I want to load in style.scss

@import 'dark-mode';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can not make an @import depending on a condition, but there is a ton of possible other approaches to this. Here is a small framework I wrote back then.

@function keyFilter($iKey, $fKey, $rKey) {
  @if ($iKey == $fKey) {
    @return $rKey;
  }
  @return $iKey;
}

@function v($key) {
  @return var(--#{$key});
}

//

$modes: (
  "&": (
    "color": #000,
  ),
  "dark": (
    "color": #fff,
  ),
);

//

@each $key, $map in $modes {
  body#{keyFilter("[#{$key}]", "[&]", null)} {
    @each $key, $value in $map {
      --#{$key}: #{$value};
    }
  }
}

To "register" a new mode just nest another map in the $modes-map, you can add as many modes as you want. Keep in mind the "&"-mode represents the default-mode.

$modes: (
  "&": (
    //...
  ),
  "dark": (
    //...
  ),
  //...
);

To register a new mode-depending variable just simply enter key and value to the respective mode.

$modes: (
  "&": (
    "color": #000,
    "bgc": #fff,
    "bgc-contrast": #eee,
    //...
  ),
  "dark": (
    "color": #fff,
    "bgc": #000,
    "bgc-contrast": #424242,
    //...
  ),
);

To call a variable just use the v($key) function.

body {
  color: v(color);
  background-color: v(bgc);
}

div.contrasted {
  background-color: v(bgc-contrast);
}

This compiling to:

body {
  --color: #000;
  --bgc: #fff;
  --bgc-contrast: #eee;
}

body[dark] {
  --color: #fff;
  --bgc: #000;
  --bgc-contrast: #424242;
}

body {
  color: var(--color);
  background-color: var(--bgc);
}

div.contrasted {
  background-color: var(--bgc-contrast);
}

Note: you do not need to declare each variable for each mode. If a variable wasn't found for the current mode, this won't throw an error.

For Example: This...

$modes: (
  "&": (
    //...
  ),
  "dark": (
    "color": #fff,
    "bgc": #000,
    "bgc-contrast": #424242,
    //...
  ),
);

//...

body {
  color: v(color);
  background-color: v(bgc);
}

div.contrasted {
  background-color: v(bgc-contrast);
}

... is totally fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...