Is it bad practice to use :root with asterisk (CSS universal selector) to override Bootstrap variables?

Viewed 34

I'm trying to theme my site, which uses Bootstrap, by modifying the Bootstrap variables. Bootstrap defines some variables against the :root element, allowing me to override them in a straightforward way:

:root {
    --bs-body-color: red;
}

However others are defined against selectors, such as --bs-navbar-color. In order to override this (and not worry about the specific selectors I need to specify), I need to apply the style universally:

:root * {
    --bs-navbar-color: blue !important;
}

Is this considered bad practice? It seems to work, and although it might be considered a bad idea for regular styles, it seems to me that it's not too much of a problem when just dealing with CSS variables.

1 Answers

This is mentioned in official documentation. When you want to override any variable you can declare them in :root without all selector and without important. It is important to import/use your override CSS after you include Bootstrap - not before.

Example:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<style>
:root {
   --bs-danger-rgb: 0,0,250;
}
</style>
<div class="bg-danger">It's blue</div>


Component variables

If you want to change a variable of a specific component, then selecting everything * is unnecessary - the variable is only in that component anyway. Whilst the * method will work, it's probably better practice to override the variable using the correct selector against which the variable is defined, such as .navbar for --bs-navbar-color, which will avoid the need to use !important. The selector you need to use for the variable is well-defined in the Bootstrap documentation. See quotes from the documentation:

Whenever possible, we’ll assign CSS variables at the base component level (e.g., .navbar for navbar and its sub-components). This reduces guessing on where and how to customize, and allows for easy modifications by our team in future updates.

Source: getbootstrap

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<style>
.navbar {
   --bs-navbar-color: blue;
}
</style>
<div class="navbar">
  <div class="navbar-text">
    It's blue
  </div>
</div>

Related