Search code examples
htmlcsstwitter-bootstrapbootstrap-5css-variables

How can I set Bootstrap 5's CSS variables using :root?


I have a Bootstrap 5 application that consumes a bunch of web components and all of the components use Bootstrap 5. I need to customize the theme on the fly inside of the parent that consumes all of these web components. My basic structure is like this:

<div>
  <div>I'm the wrapper around many web components</div>
  <abc-comp />
  <xyz-comp />
</div>

I would like to be able to pierce the shadow DOM of abc-comp and xyz-comp by setting Bootstrap's variables in the consumer.

I see that Bootstrap 5 has CSS variables so I am trying to override those variables by setting them in my own CSS :root styling like this:

:root {
  --bs-primary: tomato;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>

<button class="btn btn-primary">
  Why is my color not tomato?
</button>

How can I set Bootstrap's CSS variables in my own stylesheets where I consume many web components that all have bootstrap as a dependency?


Solution

  • The version of Bootstrap you are using apparently doesn't support customization via custom variables. At least for customization of button colors. Try using v. 5.2 which is beta for now: https://getbootstrap.com/docs/5.2/getting-started/introduction/

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous" />
    
    <style>
    .btn-primary {
      --bs-btn-bg: tomato;
      --bs-btn-border-color: tomato;
    }
    </style>
    
    <button class="btn btn-primary">
     I like tomato!
    </button>