[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

How to toggle many css styles to make a dark mode?

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #10061
    aaron
    Participant

    I’m using HTML, CSS and JavaScript to build my website. I want to add a Darkmode switch button, so by clicking, it will toggle to Dark/ Light mode, but my JavaScript script applies only for one css style – body. But actually, I have many div‘s, which are light, but they are not changed by color.

    Here’s my HTML code (with JS <script> container):

    How can I solve the problem, so by clicking the button I can make my website dark mode?

    function darkMode() {
      var element = document.body
      element.classList.toggle("dark-mode");
      element.classList.toggle("yeaaaaaa");
    }
    body {
      font-family: 'Montserrat', sans-serif;
      background-color: #fff;
    }
    
    .dark_mode {
      background-color: #000;
    }
    
    .yeaaaaaa {
      background-color: #111;
    }
    
    
    /* main styles */
    
    .main {
      display: grid;
      background-color: #f5f7fa;
      grid-template-columns: 22.15em auto;
      grid-template-rows: auto auto;
    }
    
    .grid-item {
      background: #1e2939;
    }
    
    .photo-coverup {
      display: flex;
      align-items: flex-end;
    }
    
    .info-name {
      color: #1e2939;
      margin-bottom: 5px;
    }
    
    .info-list {
      color: #1e2939;
      margin-bottom: 25px;
    }
    
    .info-yee {
      color: #1e2939;
      width: 400px;
    }
    
    
    /* about styles */
    
    .about {
      background-color: #F1F9fc;
      padding: 15px 120px 10px 50px;
    }
    
    .info {
      color: #1e2939;
    }
    
    .texx-alt {
      font-style: normal;
      color: black;
    }
    
    #delegar {
      position: fixed;
      right: 10px;
      top: 10px;
      width: 90px;
      height: 35px;
      border: none;
      outline: none;
      color: #87c9f5;
      background: #1e2939;
      cursor: pointer;
      z-index: 0;
      border-radius: 15px 0 0 15px;
      -webkit-transition: ease-in 1s;
      transition: color 1s;
    }
    
    #delegar:hover {
      color: #1e2939;
      background-color: #87c9f5;
      font-weight: bold;
    }
    <!--Main-->
    <div class="main grid">
      <div class="photo-coverup grid-item">
        <img src="img/Profile pic.jpg" alt="Dude Pic" class="photo">
      </div>
      <!--About User-->
      <span>
            <div class="about grid-item yeaaaaaa">
              <p class="info">
              <h2 class="info">Developer and Graphic Designer</h2>
              <h1 class="info-name">George Mos</h1>
              <p class="info-yee">
                My name is George (GMos) Mos. I'm a graphic designer and programmer. I have:
              </p>
              <ul class="info-list">
                <li class="info-section-list-component">4-year-experience in Adobe Photoshop and Adobe Illustrator</li>
                <li class="info-section-list-component">3-year-experience in programming
                  (Python, HTML5, Bash and JavaScript)</li>
              </ul>
              <p class="info">I'm from Ukraine, Kyiv. I work as a freelancer and, usually, my work consists
                of creating logos, wallpapers, art and/
                or making softwares, programs and websites. My life motto: "Optimistic and ambitious"
              </p>
              <p class="info">In my spare time I often lay back in Discord either texting or taking part in a voice
                channels. If you wanna join, don't hesitate yourself by following the "Discord" link in "Social Media"
                section! (or you can just <a href="https://discord.gg/PGkJgQtCwZ" class="texx-alt">click here</a> though)
              </p>
              </p>
            </div>
          </span>
      <div>
        <button onclick="darkMode()" id="delegar">Dark Mode</button>
      </div>
    #10065
    sean-kendle
    Participant

    Just add the class dark-mode to your body tag with JavaScript, then define all your dark styles with .dark-mode in front of them, like this:

    a {
        color: #330033; /* or whatever dark color */
    }
    
    .dark-mode a {
        color: white; /* or whatever light color */
    }
    

    For more info on CSS specificity and cascading, see this page:

    https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

    I recommend grouping all dark mode styles together with a comment above them, like this /* Dark mode styles: */, and put them toward the bottom of your stylesheet (above any responsive breakpoints), so they’re together, and they’re after your regular styles – because CSS takes the last defined style (hence, cascading). That way you don’t run into problems with re-defining styles. Make sure all overriding styles have more specificity than the ones they’re attempting to override. Try to avoid use of !important where possible.

    #10062
    shawn-caza
    Participant

    While Sean Kendle’s approach can work, there’s other options that are probably cleaner and less effort to implement if you don’t need to worry about older browsers. I offer a few ideas to consider below. CSS variables is the most important one.

    SCSS

    To simplify working in css, you might to consider using scss.

    With scss instead of prefacing all dark style with .dark-mode you could nest all your dark-mode styles inside one dark mode definition. For example:

    .dark-mode{
    
        background-color: black;
    
        a{
            color: white;
        }
    
        //any other dark styles
    
    }
    

    User preference media queries

    To improve things further, consider that the OS often allows people to specify a dark mode preference at the system level, and we now have a well-supported media query in CSS to detect that OS preference:

    @media (prefers-color-scheme: dark) {
    
     //dark styles here.
    
    }
    

    Jason Pamental has an interesting article here on using the prefers dark media query, in addition to a user toggle on the site itself, and using css variables to switch styles in a simple powerful way. There’s a demo of the concept here.

    CSS Variables

    If you are able to use css variables, your could just define the css once, and simply flip the variables to switch to dark mode. This is a simplified version of the css from the above demo to illustrate how to change colours for dark mode with variables:

    :root {
    
      --color-dark: #3a3a3a;
      --color-light: #eee;
      
      --color-text: var(--color-dark);
      --color-background: var(--color-light);
      
    }
    
    body {
      background-color: var(--color-background);
      color: var(--color-text);
      transition: background-color 0.25s ease, color 0.25s ease;
    }
    
    
    .dark-mode {
      /* flip the light and dark variables */
      --color-text: var(--color-light);
      --color-background: var(--color-dark);
    }
    
    #10063
    theshininglemonade
    Participant

    I would use CSS variables (w3schools). You can create a few variables in the :root, like for a bright background or the text color, then you assign those to the different elements. If you want to change to dark mode, you only have to change the variables accordingly (the text to a bright color and the background to a dark color):

    :root {
        --text: #1e2939;
        --bg: #F1F9fc;
    }
    
    body {
        font-family: 'Montserrat', sans-serif;
        background-color: #fff;
    }
    
    .yeaaaaaa {
      background-color: #111;
    }
      
      /* main styles */
      .main {
        display: grid;
        background-color: #f5f7fa;
        grid-template-columns: 22.15em auto;
        grid-template-rows: auto auto;
      }
      
      .grid-item {
        background: #1e2939;
      }
      
      .photo-coverup {
        display: flex;
        align-items: flex-end;
      }
    
      .info-name {
        color: var(--text);
        margin-bottom: 5px;
      }
      
      .info-list {
        color: var(--text);
        margin-bottom: 25px;
      }
      
      .info-yee {
        color: var(--text);
        width: 400px;
      }
    
      /* about styles */
      .about {
        background-color: var(--bg);
        padding: 15px 120px 10px 50px;
      }
    
    .info {
        color: var(--text);
      }
    
    .texx-alt {
        font-style: normal;
        color: black;
    }
    
    #delegar {
        position:fixed;
        right: 10px;
        top: 10px;
        width: 90px;
        height: 35px;
        border: none;
        outline: none;
        color: #87c9f5;
        background: var(--text);
        cursor: pointer;
        z-index: 0;
        border-radius: 15px 0 0 15px;
        -webkit-transition: ease-in 1s;
        transition: color 1s;
    }
    
    #delegar:hover {
      color: #1e2939;
      background-color: #87c9f5;
      font-weight: bold;
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
    
      </head>
    
      <body>
        <!--Main-->
        <div class="main grid">
          <div class="photo-coverup grid-item">
            <img src="img/Profile pic.jpg" alt="Dude Pic" class="photo">
          </div>
          <!--About User-->
          <span>
            <div class="about grid-item yeaaaaaa">
              <p class="info">
              <h2 class="info">Developer and Graphic Designer</h2>
              <h1 class="info-name">George Mos</h1>
              <p class="info-yee">
                My name is George (GMos) Mos. I'm a graphic designer and programmer. I have:
              </p>
              <ul class="info-list">
                <li class="info-section-list-component">4-year-experience in Adobe Photoshop and Adobe Illustrator</li>
                <li class="info-section-list-component">3-year-experience in programming
                  (Python, HTML5, Bash and JavaScript)</li>
              </ul>
              <p class="info">I'm from Ukraine, Kyiv. I work as a freelancer and, usually, my work consists
                of creating logos, wallpapers, art and/
                or making softwares, programs and websites. My life motto: "Optimistic and ambitious"
              </p>
              <p class="info">In my spare time I often lay back in Discord either texting or taking part in a voice
                channels. If you wanna join, don't hesitate yourself by following the "Discord" link in "Social Media"
                section! (or you can just <a href="https://discord.gg/PGkJgQtCwZ" class="texx-alt">click here</a> though)
              </p>
              </p>
            </div>
          </span>
        <div>
          <button id="delegar">Dark Mode</button>
        </div>
        <script>
            const button = document.getElementById('delegar');
            button.addEventListener('click', (event) => {
                if (button.innerHTML === "Dark Mode") {
                    document.documentElement.style.setProperty('--text', '#eee');
                    document.documentElement.style.setProperty('--bg', '#1e2939');
                    button.innerHTML = "Light Mode";
                } else {
                    document.documentElement.style.setProperty('--text', '#1e2939');
                    document.documentElement.style.setProperty('--bg', '#F1F9fc');
                    button.innerHTML = "Dark Mode";
                }
            });
        </script>
      </body>
    </html>
    #10064
    voaneves
    Participant

    Just to show you a working example, you can use prefers-color-scheme for automatic toggling and also create a dark-mode and light-mode classes, for manual toggling.

    document.getElementById("theme").addEventListener("click", function () {
        if (window.matchMedia("(prefers-color-scheme: dark)").matches) document.body.classList.toggle("light-mode");
        else document.body.classList.toggle("dark-mode");
      });
    @media (prefers-color-scheme: dark) {
        :root {
            --color-primary: #0a0a0a;
            --color-secondary: #339eff;
        }
    }
    
    @media (prefers-color-scheme: light) {
        :root {
            --color-primary: #ffffff;
            --color-secondary: #ff7e33;
        }
    }
    
    .light-mode {
        --color-primary: #ffffff;
        --color-secondary: #ff7e33;
    }
    
    .dark-mode {
        --color-primary: #0a0a0a;
        --color-secondary: #339eff;
    }
    
    body {
        background-color: var(--color-primary);
        color: var(--color-secondary);
    }
    <!DOCTYPE html>
    <html lang="pt-BR" xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br">
      <head>
        <meta name="color-scheme" content="dark light" />
        <meta name="theme-color" media="(prefers-color-scheme: dark)" />
        <meta name="theme-color" media="(prefers-color-scheme: light)" />
      </head>
      <body>
        This is a test
    
        <button id="theme">Change theme</button>
      </body>
    </html>

    You can change it to your needs, but this is according to web.dev. Remember to set the prefers-color-scheme colors, and then change it automatically or by a manual toggle, using the .light-mode and .dark-mode classes.

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.