bootstrap-4

Understanding Bootstrap 5 variables import order overrides


I do not understand the following situation. I have this order of SCSS variables imports in my app.scss

@import '~/node_modules/bootstrap/scss/functions';
@import '~/node_modules/bootstrap/scss/variables';
@import '~/node_modules/bootstrap/scss/mixins.scss';

@import 'variables'; // overrides

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

As per the Bootstrap docs, this should be the correct order to import to appropriately override Bootstrap variables. In my variables I have the following CSS:

$font-size-base: 0.8rem;
$font-weight-medium: 500;
$font-weight-semi-bold: 600;

$h1-font-size: $font-size-base * 2.6;
$h4-font-size: $font-size-base * 1.2;
$h5-font-size: $font-size-base * 1.1;

But there is something that confuses me. As you can see the $font-size-base: 0.8rem; is an override, but for some reason, the default variables of Bootstrap do not pick this up. When I wanna have the applied new font-size-base for the default variables of Bootstrap, I need to specifically import them in here also, like so:

$h3-font-size: $font-size-base * 1.75;

Can anyone tell me why that is? I do not wanna import $h3-font-size as the multiplier isn't changing to the default, I just want Bootstrap to pick up the new $font-size-base in their defaults.


Solution

  • Correct Import Order in app.scss:

    // Import Bootstrap's functions first
    @import '~/node_modules/bootstrap/scss/functions';
    
    // Override Bootstrap variables here (in your custom 'variables' file)
    @import 'variables';
    
    /*
    The following variable overrides are as mentioned by you, defined in the 'variables' file:
    
    
    $font-size-base: 0.8rem;
    $font-weight-medium: 500;
    $font-weight-semi-bold: 600;
    
    $h1-font-size: $font-size-base * 2.6;
    $h4-font-size: $font-size-base * 1.2;
    $h5-font-size: $font-size-base * 1.1;
    */
    
    // Import Bootstrap’s variables and mixins
    @import '~/node_modules/bootstrap/scss/variables';
    @import '~/node_modules/bootstrap/scss/mixins';
    
    // Finally, import Bootstrap’s main styles
    @import '~/node_modules/bootstrap/scss/bootstrap';
    

    UPDATE

    Based on our discussion in the comments with the questioner, and considering the feedback "Makes sense now, if wanna edit your answer to reflect your comment I am happy to accept it." the updated version of the answer is:

    If you need to both override default Bootstrap variables and use Bootstrap’s variables in your custom file, it’s not possible to do so in a single file. Instead, you should separate your custom variables into two files: one for overrides and another for using Bootstrap variables. Import the overrides file first, then Bootstrap’s variables, and finally the file that uses Bootstrap variables after the Bootstrap imports.