Automatic Dark Mode For Django Template Using Bootstrap

How to set your website theme to dark when using bootstrap in Django templates
July 20, 2024 by
Automatic Dark Mode For Django Template Using Bootstrap
Hamed Mohammadi
| No comments yet

Bootstrap 5.3.0 introduced built-in support for color modes, including dark mode. This simplifies the process of implementing automatic dark mode based on user preference.

Many developers use bootstrap for their website styling. When you use bootstrap for styling your Django templates, it is extremely easy to change your website color mode to dark or light based on the user preference set in her browser.

Bootstrap 5 offers a data-bs-theme attribute that allows you to control the color mode globally or on specific elements. You can use this attribute to set the color mode of your website by help from bootstrap.

First you need to add this attribute to your html header. In your base template (e.g., base.html), add the data-bs-theme attribute to the <html> tag. Initially, set it to "light":

<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
  ...
</head>
<body>
  ...
</body>
</html>

If a user selected theme color is dark this changes nothing and the user browses your website happily. To change the color mode to dark if the user color mode is dark we can use JavaScript.

You can write a short JavaScript snippet to check the user's preferred color scheme on page load and set the data-bs-theme attribute accordingly. Here's an example:

const htmlElement = document.documentElement;
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

if (prefersDark) {
  htmlElement.setAttribute('data-bs-theme', 'dark');
}


If the user uses light color mode bootstrap uses the default light color mode. If the user has set the preferred color mode to dark then your website is shown in dark mode by bootstrap.

This is all you need to have your Django website show all your pages in light or dark color theme based on user preference set in her browser.


Automatic Dark Mode For Django Template Using Bootstrap
Hamed Mohammadi July 20, 2024
Share this post
Archive

Please visit our blog at:

https://zehabsd.com/blog

A platform for Flash Stories:

https://readflashy.com

A platform for Persian Literature Lovers:

https://sarayesokhan.com

Sign in to leave a comment