skip to Main Content

TLDR: I want to change Bootstrap SASS variable value depending on a CSS selector

PS. I know I can manually assign the color directly but I’m trying to understand how to override Bootstrap CSS properties by using the SASS variables in combination with CSS selectors.


example (contents of Apps.scss from the link below)

@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";

//the 2  lines below work but both H3 text color are the same
$headings-color: blue; //this works
$body-color: green; //works too if you comment out headings-color

h3.red {
  $headings-color: red; //does not work
}

h3.blue {
  $headings-color: blue; //does not work
}

@import "bootstrap/scss/bootstrap";

Here’s the link to the sample code that might better explain what I want (might need to click the refresh button on the preview tab to get it to work) => click here for codesandbox.io

Any ideas on how to get it to work?

2

Answers


  1. Use "!global" after colors and before ";". It should then override the global variable with the tagged one.

    Login or Signup to reply.
  2. SASS variables are used by SASS code. If you simply re-declare a global variable within a block and don’t use its value, nothing will happen. So you need to add some CSS properties that can use this re-declared variable.

    For example:

    h3.red {
      $headings-color: red;
      color: $headings-color;
    }
    
    h3.blue {
      $headings-color: blue;
      color: $headings-color;
    }
    

    Think of this code as a preprocessor instruction. This means that selectors h1.red and h1.blue will be created, containing only what was written in the corresponding SCSS blocks.

    This is the output CSS code that will be used by the browser:

    h3.red {
      color: red;
    }
    
    h3.blue {
      color: blue;
    }
    

    In your case, the resulting CSS will be empty, because the SCSS code doesn’t contain any CSS properties:

    // code generated by your SCSS code
    h3.red {
    }
    
    h3.blue {
    }
    
    // here is the code generated by bootstrap/scss/bootstrap
    // ...
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search