Search code examples
csscolorsalertbootstrap-5

Bootstrap 5.1+ How to change colors (text, background, border) of alerts of a specific color (like alert-warning) inside custom _variables.scss


I am using a custom _variables.scss file, that is imported like that:

@import url('https://fonts.googleapis.com/css?family=Nunito');
@import 'variables';
@import 'bootstrap/scss/bootstrap';
@import "custom";

I tried to change the alert color like that, but this does nothing:

$alert-color: $orange;
$alert-bg: $orange;
$alert-border-color: $orange;

I know using css-variables is another way to do it. but i would like to have one central place to manage custom changes as far as possible.

My current Bootstrap version is 5.1. The solution should also work in 5.2, since i will update soon.


Solution

  • At the time of writing this answer, none of the following vars exist in Bootstrap: $alert-color, $alert-bg nor $alert-border-color.

    The value you try to modify are defined like this in Bootstrap source code:

    .alert {
      --#{$prefix}alert-bg: transparent;
      --#{$prefix}alert-color: inherit;
      --#{$prefix}alert-border-color: transparent;
    
      color: var(--#{$prefix}alert-color);
      background-color: var(--#{$prefix}alert-bg);
      border: var(--#{$prefix}alert-border);
    }
    

    So as you said you might want to use CSS vars instead (the following example modify the color or all alerts as orange):

    .alert {
      --#{$prefix}alert-color: #{$orange}; // or --bs-alert-color: #{$orange};
    }
    

    There's another way to do this kind of things but it will only add a new theme color for each component and I'm not sure that's what you want:

    $custom-colors: (
      "custom-color": #f61
    );
    
    $theme-colors: map-merge($theme-colors, $custom-colors);
    

    So you'll be able to use:

    <div class="alert alert-custom-color" role="alert">
      A simple custom color alert—check it out!
    </div>
    

    But also

    <button type="button" class="btn btn-custom-color">Primary</button>
    

    Third possibility:

    .alert-custom-color { // Creating your own class
    // .alert would modify all the alerts
    // .alert-warning would modify the rendering only for this one
      @include alert-variant(green, violet, yellow);
    }