Is there a way to switch the entire page to dark mode with a toggle feature

I successfully implemented a dark theme and light theme toggle with the click of a checkbox in both HTML and Flask. However, I am facing an issue where the dark theme only covers some div elements and not the entire page. The margins still appear in light theme... Below is the CSS code snippet:

.container {
  display: flow;
  width: 100%;
  height: 100%;
  background: var(--color-secondary);
}
        .theme-light {
            --color-primary: #0060df;
            --color-secondary: #fbfbfe;
            --color-accent: #fd6f53;
            --font-color: #000000;
        }

        .theme-dark {
            --color-primary: #17ed90;
            --color-secondary: #2a2c2d;
            --color-accent: #12cdea;
            --font-color: #ffffff;
            width: 100%;
            height: 100%;
        }

Here is how the current dark theme looks: https://i.sstatic.net/dNSTT.png

Answer №1

body{
   background: var(--color-secondary);
}
.container {
   display: flow;
   width: 100%;
   height: 100%;
   background: var(--color-secondary);
}
    .theme-light {
        --color-primary: #0088ff;
        --color-secondary: #f0f0f2;
        --color-accent: #ff7744;
        --font-color: #111111;
    }

    .theme-dark {
        --color-primary: #22ee99;
        --color-secondary: #292c2e;
        --color-accent: #33bbee;
        --font-color: #dddddd;
        width: 100%;
        height: 100%;
    }

Answer №2

To implement a dark theme and a light theme for your webpage, create classes that differ in their styling for each theme. Then, use JavaScript to dynamically change between the dark and light themes based on a checkbox selection.

document.querySelector("#theme-switcher").onchange = function() {
  var self = this;
  document.querySelectorAll("*").forEach(function(elem) {
    if(self.checked && elem.className.indexOf("light") !== -1) {
      elem.className = elem.className.replace("light", "dark");
    }else if(!self.checked && elem.className.indexOf("dark") !== -1) {
      elem.className = elem.className.replace("dark", "light");
    }
  });
} 
.light-text {
  color: black;
}
.dark-text {
  color: white;
}
.light-mode {
  background-color: #eee;
}
.dark-mode {
  background-color: #333;
}
<div class="light-mode">
  <input id="theme-switcher" type="checkbox">

  <p class="light-text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus quam. Sed purus. Vivamus eros augue, venenatis a, pretium non, eleifend at, wisi. Fusce vestibulum. Vivamus dui. Nullam sed arcu eu eros pretium tincidunt. Fusce leo diam, pharetra nec, venenatis vitae, consequat sed, est. Aliquam id mi. Praesent ligula. Vivamus vehicula nulla vitae purus. Morbi mauris. Aliquam erat volutpat. Donec a nisl. Vivamus mattis lacinia sapien.</p>

  <p class="light-text">Morbi commodo luctus sem. Morbi mattis ultricies lorem. Nunc semper urna eget wisi. Pellentesque pellentesque, pede at auctor porta, sem metus consectetuer eros, ut vestibulum leo lacus eu libero. Nullam libero mauris, feugiat a, lacinia et, tincidunt et, nunc. Nunc lorem.</p>

  <p class="light-text">Ut ligula mauris, ornare eget, consequat sed, porta nec, massa. Donec ligula. Phasellus turpis elit, porttitor nec, vestibulum at, hendrerit vel, sapien. Donec justo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean ut magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean nunc. Maecenas vulputate lorem ac dolor. Ut sed sapien. Ut placerat.</p>

  <p class="light-text">In hac habitasse platea dictumst. Fusce vitae mauris. Aliquam a mi at quam posuere venenatis. Proin auctor, lacus eu vestibulum venenatis, turpis turpis porta lectus, at tempus lorem dui id libero. Suspendisse elementum, nunc et viverra viverra, orci nunc molestie nunc, quis dignissim magna lorem vitae urna. Donec tortor. Morbi convallis rutrum justo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tincidunt.</p>

  <p class="light-text">Nunc hendrerit semper nibh. Maecenas malesuada, arcu a sodales ultricies, sem felis scelerisque arcu, sed tempor velit mauris ut elit. Sed ut libero eu wisi eleifend condimentum. Proin justo. Fusce fringilla. In magna. Donec ac sem eget risus fermentum blandit. Morbi tristique arcu id eros. Curabitur sem. Suspendisse a tellus. Quisque nisl erat, luctus in, dictum nec, euismod ut, odio.
  Sed turpis nulla, mollis ac, malesuada sit amet, mattis eu, mi. Praesent tempor, erat ac consequat volutpat, eros odio rutrum eros, eget blandit enim massa vel velit. Vestibulum vestibulum orci eu nulla. Pellentesque augue augue, suscipit eu, auctor nec, auctor id, tortor.</p>

  <p class="light-text">Phasellus id leo vel orci luctus convallis. Donec rhoncus rhoncus lorem. Phasellus cursus. Mauris orci. Donec vel lacus sit amet urna tristique ornare. Vivamus fermentum posuere lectus. Vestibulum mollis lobortis diam. Nam feugiat mauris sed erat. Aliquam erat volutpat. Ut sed orci.</p>
</div>

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

Adjust the Bootstrap row height to both occupy the full height while also being limited by the height of a designated container

Here's a puzzling question.. I've got a container with multiple rows, and I want these rows to completely fill the container's height without overflowing. I'm trying to avoid manually setting the row heights. When I add class="h-1 ...

Exploring the basics of utilizing React Testing Library to test a component - a beginner's dive into this innovative testing tool

I've been working on learning how to test 2 components using react-testing-library, but I've hit a roadblock. The component in question is NestedLists.js import React from 'react' export const NestedLists = ({filteredData}) => { ...

Transform your SVG graphics in a div to PNG format with ease using Raphaël JS

As a newcomer to Raphaël and JavaScript, I have a question about how to save SVG (in a div) to PNG using JavaScript. Despite reading many articles on the subject, such as utilizing canvg (https://code.google.com/p/canvg/) and canvas.toDataURL('image/ ...

JavaScript declares that the intersection property is missing

Initially, I have a variable of type IPerson[], but after undergoing a couple of mapping iterations, it should have an added _id property, transforming it into Array<IPerson & IWithId>. However, upon trying to access the _id property in the fourt ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

Why does jwplayer function properly on desktops but not consistently on all mobile devices?

Here is how I set it up: autostart:true file:"//strlb.nava.hu/lbs/navahus/_definst_/amlst:2334206?type=m3u&sessid=U2FsdGVkX1%2BT8isbmDU7Vz56rK8KVCo2xKgOLwwR5JUSq5m5GfKrL4HM%2FrbhwdyJJ0gyyK0X6%2FrAbTjfnsBAqg%3D%3D_2" height:360 id:"videoPlayer" preloa ...

Tips for arranging divs in Bootstrap 5 to position one above the other

I have chosen to utilize Bootstrap 5 for my website project with the aim of enhancing its responsiveness on all devices. Specifically, I am seeking a way to ensure that when visitors access the site from a mobile device, the image-containing div appears a ...

Steps to trigger an alert when the entered quantity exceeds the current stock levels

After developing an IMS System, I encountered a problem where my stock is going into negative figures. To resolve this issue, my primary goal is to trigger an alert whenever the quantity entered by a user exceeds the available stock. For example, if a us ...

Ways to incorporate gentle page breaks into an HTML document

My task involves creating an XSL script to analyze various XML files that share a similar structure. The aim is to parse these XMLs and transform them into HTML pages. For longer XML documents, I want the resulting HTML page to be paginated (meaning the pa ...

The fading effects are not functioning as expected in the following code

Hey there, I'm not the most tech-savvy person, but I managed to come up with this code for page redirection. Unfortunately, I couldn't quite get the fade out and fade in effects to work properly when executing it. If anyone out there can help me ...

Error: The studentsList is not iterable. Issue encountered during Jasmine Unit Testing in Angular 2

How can I effectively test the forEach loop in jasmine with karma? Below is the code for the component: getData(studentsList:any, day:any, game:any){ let strength:any; let location:string; if(studentsList){ studentsList.forEach( value =& ...

Retrieve the child elements of several tags using selenium

Is there a way to retrieve all sub elements of multiple elements that share the same class? <html> <body> <h3 class="searchresult"> <a href='/lorem1'>Text1</a> </h3> <h3 class="searchresult ...

The input value is displaying one value, but the output is showing a different value

I am encountering a unique issue and could really use some assistance. <input class="testVal" type="number" id="GT_FIRING_TEMPERATURE" value="-17" name="degC" onchange="angular.element(this).scope().unitConversion(value,name, id)"> Despite the valu ...

Concealing Bootstrap Dialog in Angular 6 through Component隐藏Angular 6中

I have been struggling to hide a bootstrap dialog from a component with no success. Here is my Dialog code: <div class="modal fade" id="loading_video_upload" tabindex="-1" role="dialog" aria-labelledby="loading_video_upload_label" aria-hidde ...

Utilizing jQuery on the newly inserted <tr> element

I have created a jQuery code that includes 3 pre-existing rows with a text box to add more similar rows. The jQuery functions are initially applied to the first 3 hard-coded rows. I am looking to extend this functionality to dynamically added rows later on ...

Is it possible in JavaScript to pass undeclared method parameters without using eval()?

Understanding from just the title can be tricky. Let me provide an example. I need a function to automatically refer to a variable that is "injected", like this: function abc() { console.log(myVariable); } I attempted to achieve this with: with({myVa ...

Exploring the use of external JavaScript functions within an AngularJS controller

Hey there! I have a method called "Mymethod()" defined in jQuery within the widjets.js file. I need to call this method in an AngularJs Controller written in Typescript. ...

How come my Ajax response is showing up above my navigation menu?

Every time I scroll my mouse, the admin cards end up covering the navbar, which is really annoying. I can't figure out where I went wrong with this issue. Any assistance would be greatly appreciated. Thank you! #mainsec { height: 100vh; width ...

What is the best way to load the contents of an HTML file into a <div> element without it behaving as an object?

Currently, I am importing an HTML file into a <div> in this manner: function load_content() { document.getElementById('content').innerHTML = '<object type="text/html" width="100%" height="100%" data="./content.html"></obj ...

Unable to integrate multiple webpack projects: Uncaught SyntaxError occurs due to a missing closing parenthesis after the argument list

My website features a section where clients can track their projects. One aspect of the site involves viewing a blueprint created using THREE.js and bundled with webpack. I have been tasked with adding another type of blueprint to the site. I have success ...