A guide on changing the background color to complement the light/dark theme in Bootstrap 5.3

In the latest version of Bootstrap, 5.3, users have the ability to select a theme for their websites. The built-in options include a Dark theme and a Light theme.

For instance, by setting

<html data-bs-theme="dark">
, you can specify that the navbar should have a light color. Conversely, if you set
<html data-bs-theme="light">
, you may want the navbar to display dark background colors.

Is there a specific Bootstrap class that can be utilized to automatically switch the colors based on the selected theme?

Experimenting with the body-* classes did not yield the desired results. I am looking for a way to toggle between the opposite of the current text-body or bg-body colors.

<nav class="navbar text-body bg-body">
       
</nav>

How can I invert the background color based on the chosen light/dark theme in Bootstrap 5.3?

Answer №1

Mr. J's method will globally reverse the styles of .bg-body and .text-body. I wonder about its practicality since it might be easier to just switch to the opposite theme.


Utilizing Nested Color Modes (JS)

salif's recommendation, known as Bootstrap's nested color modes, seems like a smart choice:

<body data-bs-theme="dark">
  <nav id="nav" data-bs-theme="light" class="navbar text-body bg-body">

By toggling both data-bs-theme attributes in your JS color mode switcher:

window.onload = function() {
  document.getElementById('themer').addEventListener('click', () => {
    const current = document.documentElement.getAttribute('data-bs-theme')
    const inverted = current == 'dark' ? 'light' : 'dark'
    document.documentElement.setAttribute('data-bs-theme', inverted)
    document.getElementById('nav').setAttribute('data-bs-theme', current)
  })
}
<html data-bs-theme="dark">

<head>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e6ebebf0f7f0f6e5f4c4b1aab7aab4a9e5e8f4ece5b5">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
  <nav data-bs-theme="light" id="nav" class="navbar text-body bg-body">
    <div class="container-fluid">
      <span class="navbar-brand mb-0 h1">Inverted navbar</span>
      <a id="themer" href="#" class="btn btn-primary m-3" role="button" data-bs-toggle="button">Toggle theme</a>
    </div>
  </nav>
</body>

</html>


Using Inverted Classes (CSS only)

If you prefer a CSS-only approach, create -inverted classes to interchange foreground and background styles:

  • .bg-body-inverted (inverted theme background) corresponds to --bs-body-color (theme foreground)
  • .text-body-inverted (inverted theme foreground) corresponds to --bs-body-bg (theme background)

These -inverted variations will invert foreground and background regardless of the color mode:

.bg-body-inverted {
  background-color: var(--bs-body-color) !important;
}

.text-body-inverted {
  color: var(--bs-body-bg) !important;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab8b5b5aea9aea8bbaa9aeff4e9f4eaf7bbb6aab2bbeb">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">

<body data-bs-theme="dark">
  <nav class="navbar text-body-inverted bg-body-inverted">
    <div class="container-fluid">
      <span class="navbar-brand text-body-inverted mb-0 h1">Inverted navbar</span>
    </div>
  </nav>
</body>

Answer №2

To accomplish this, you can utilize css variables in your code.

Start by specifying your primary theme colors in the :root selector

:root {
  --primary-color: #007bff;
  --secondary-color: #6c757d;
  --text-color: #343a40;
  --background-color: #f8f9fa;
}

Next, assign colors for the .bg-primary class based on the selected theme:

[data-theme=light] {
  --bg-primary: var(--secondary-color);
  --text-primary: var(--text-color);
}

And for the .bg-primary class under the "dark" theme:

[data-theme=dark] {
  --bg-primary: var(--primary-color);
  --text-primary: var(--background-color);
}

By switching between themes, the background and text colors for the nav should adjust accordingly.

Bootstrap 5.3 provides its own theme color variables:

https://i.sstatic.net/GK7W4.png

Feel free to utilize these predefined variables instead of creating your own.

I hope this explanation is helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with jQuery Quicksand's CSS rendering in Internet Explorer and Firefox browsers, but not affecting Chrome

I'm attempting to achieve an icon-swapping effect using jQuery+quicksand. Although it works seamlessly in Chrome, I am encountering issues with IE and Firefox. Given that the more intricate quicksand demos function flawlessly across all browsers, I su ...

Styling CSS variables uniquely

I have limited knowledge of HTML and CSS, so I am unsure how to search for a similar post on StackOverflow. My apologies if this is a duplicate question. I am looking to achieve the following: margin-horizontal { margin-left: value; margin-right: va ...

Adding a button to the right of a text-field input in Vuetify app

I need advice on the best way to use Vuetify in order to display a button to the right of a text-field (attached). I've checked the main site for information but couldn't find anything related to this specific scenario. https://i.sstatic.net/Pp ...

Seamless animated loading gif as a looping background visual

Is there a way to find a GIF that can be used as a repeated background on an HTML element, creating the illusion of a seamless block? https://i.sstatic.net/5BKxW.gif (source: opengraphicdesign.com) I am looking for an 80x80 GIF that can be repeated as ...

On smaller screens in portrait mode, CSS automatically incorporates margin adjustments

Here is the code I am working with: <html> <head> <style> body { margin: auto; width: 720px; } </style> </head> <body> <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ip ...

Show the form when the button is clicked

I want to create an application that allows users to click on a button in the top right corner (check image) to hide one div (topics) and show another div (a form for adding a new topic). Here is what it looks like: https://i.stack.imgur.com/YeRTw.png ...

Attempting to achieve the simultaneous display of an image overlay and image zoom when hovering over the mouse

I'm struggling to display an image overlay and image zoom simultaneously when hovering the mouse. After adding the image zoom effect, the overlay disappears. It seems like one transition is overriding the other. Whenever the zoom works, the overlay do ...

The margin of the parent container is influencing the margin of the child element

Purple Working on displaying a rectangle shape in a browser using divs in my React project. Everything works fine, but when I add margin to the parent base and then draw the boxes, there's some space between the mouse cursor and the actual box. The ...

How to centrally align tabs in Material-UI AppBar using ReactJS

I'm developing a React Application using Material-UI and facing difficulty in centering the 3 tabs within the blue AppBar. Currently, they are aligned to the left like this: (unable to embed images at the moment, apologies) This is the code snippet ...

Froala text area is unexpectedly visible when I attempt to cover it with a partially see-through mask

The website I'm currently developing features a semi-transparent overlay that dims the screen with a light-colored message displayed on top. This overlay and message are shown whenever there is a background process running. Everything was running smoo ...

Problem with datepicker interface not aligning properly with Bootstrap grid

I am encountering a challenge with aligning the input controls in my UI design. Specifically, I am trying to create rectangular borders/containers around each set of input controls and looking for a way to achieve this using Booststrap. For reference, y ...

Struggling to connect CSS to HTML on Github Pages

I'm new to using Github, and I noticed that when I open the website, my HTML code is displaying without the associated CSS. Here is a snippet of my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

Utilizing checkboxes to toggle the visibility of a div element with varying headings

By toggling a checkbox, I aim to show or hide the same div with a different heading. $('#cbxShowHide').click(function() { this.checked ? $('#block').show(1000) : $('#block').hide(1000); }); #block { display: none; bac ...

The functionality of hiding and displaying div elements is malfunctioning

I am currently working on a side menu that contains two buttons. My goal is to display the content of the profile div by default, and when the user clicks on the My reviews button in the sidebar, I want to hide the content of the profile div and show the r ...

simultaneous image hover effect for all images

I am experiencing an issue with my CSS and Bootstrap hover effect. The overlay tags are enclosed within a div class, but they all hover simultaneously. Each overlay belongs to a different Bootstrap grid, yet the effect extends even to the empty spaces betw ...

Chart.js encountered an uncaught TypeError when attempting to resolve the module specifier for "@kurkle/color"

Currently, I am utilizing Chart.js 4.2 within a Laravel project that is integrated with Bootstrap 5.1. The chart is functioning as expected; however, an error in the console has been causing frustration: Uncaught TypeError: Failed to resolve module specifi ...

What is the best way to assign a unique ID to every element in this situation?

Here is the given code: var words = ['ac', 'bd', 'bf', 'uy', 'ca']; document.getElementById("wordTable").innerHTML = arr2tbl(2); function arr2tbl(ncols) { return words.reduce((a, c, i) => { ...

Order of stacked divs with absolute positioning

I'm struggling to make a photo expand when hovered over without it expanding under the existing content. My current HTML and CSS code is as follows: .userCard {width:360px;height:180px;border:1px solid black;float:left;margin:10px;position:relative ...

NavigateToTop/BackToTheBeginning

I'm facing a challenge with a page layout that involves two vertical div's - one for the menu on the left and another for loading content on the right. My goal is to utilize the .scrollintoview() function on the menu div so that when a link is cl ...

Collapsing table row in Bootstrap upon button click within the same row

The snippet showcases a basic table with one row containing a button group. Upon clicking the 'main' button (the reset button), the following table row will appear. This behavior is intended only when clicking on the table row itself, not the but ...