Overwrite Bootstrap 4 Sass variables with CSS variables?

Viewed 3549

I am trying to overwrite default Primary Sass variable in Bootstrap 4 to a custom color using CSS variables in an Angular application, like this:

styles.scss

:root {
  --primary: #00695c;
}

$myPrimary: var(--primary);

$primary: $myPrimary; // This does not work

@import '../node_modules/bootstrap/scss/bootstrap';

I get this error when compiling my application:

Failed to compile.

./src/styles.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--15-3!./src/styles.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):

undefined
                                         ^
      $color: var(--primary) is not a color.
    ╷
181 │ $link-hover-color:                        darken($link-color, 15%) !default;
    │                                           ^^^^^^^^^^^^^^^^^^^^^^^^
    ╵
  node_modules\bootstrap\scss\_variables.scss 181:43  @import
  node_modules\bootstrap\scss\bootstrap.scss 9:9      @import
  stdin 19:9                                          root stylesheet
      in C:\Work\node_modules\bootstrap\scss\_variables.scss (line 181, column 43)

Is there a way to solve this issue and overwrite bootstrap sass variables using css variables?

There is another related question, But I am unable to solve my issue with it.

Update

Actually I've created an Angular component library to be used internally. I have implemented Theming in this library using CSS variables, so I can change their values dynamically and allow the user to select a theme for the application.

So inside my library I have different theme files, Below is one of them:

theme.scss

@import './library-styles-to-be-used-in-app.scss';

:root {
  --primary: #00695c;
  --secondary: #f4f5f6;
}

Now, I import this theme file inside my angular app styles.scss file like this:

@import '../dist/library/styles/theme.scss';
@import '../node_modules/bootstrap/scss/bootstrap';

See the images below bootstrap css variables are already overwritten, but if I use bootstrap class like btn btn-primary it still shows that old blue color.

Bootstrap CSS Variables

My Theme CSS Variables

2 Answers

This is not possible since CSS custom properties and SASS variables are two seperate things.

CSS custom properties can change during runtime via Javascript.
SASS variables on the other hand are static, they will be generated and are then hardcoded values in the .css-File. For example, the darken() functionality from SASS takes the input string (for example a hex-value) and outputs a darkened version of this hex-value.

But bootstrap already uses CSS custom properties, so maybe you are just using them in the wrong way. Maybe if you expand what you want to achieve maybe we can help you better.

For now the only answer we can give you is: This is not possible.

Related