In Bootstrap 5.3, we are able to specify a theme to use for the site. Out of the box there are two supported theme Dark and Light.
If I set my <html data-bs-theme="dark">
, I want to set the site navbar to a light color. At the same time, when setting <html data-bs-theme="light">
I want the navbar to have dark background colors.
If there a specific class in Bootstrap that can be used to invert the colors based on the current theme?
I tried using the body-*
classes to accomplish, but that does not do what I want. I want to select the opposite of the current text-body
or bg-body
.
<nav class="navbar text-body bg-body">
</nav>
How to invert background color based on the light/dark theme in Bootstrap 5.3?
2
Answers
You can achieve this using css variables.
First you define your main theme colours in :root
Then you assign a colour to use for the
.bg-body
class with the "light" theme:And which colour to use for
.bg-body
with the "dark" theme:Now when you toggle between themes, the
nav
background and text colour should update accordingly.Bootstrap 5.3 defines it’s own theme colour variables:
Feel free to use these instead of the ones I declared above.
I hope this helps.
Mr. J’s approach will invert
.bg-body
and.text-body
globally. I’m not sure how useful that is because you could (should) just use the opposite theme in that case.Nested color modes (JS)
I would use salif’s suggestion, which Bootstrap calls nested color modes:
Then in your JS color mode toggler, flip both
data-bs-theme
attributes:Inverted classes (CSS only)
If you want to do it with just CSS, define
-inverted
classes to swap foreground and background:.bg-body-inverted
(inverted theme background) gets mapped to--bs-body-color
(theme foreground).text-body-inverted
(inverted theme foreground) gets mapped to--bs-body-bg
(theme background)These
-inverted
versions will invert fg/bg regardless of color mode: