skip to Main Content

I wanna make a website with ‘day’ and ‘night mode’, basically just light and dark version of a website and I have no clue how to do it the best way.

I’ve tried just making two HTML files with different CSS’s included, then i tried changing CSS using PHP.

None of my tries were satisfying, I need something universal and easy to implement.

Thanks for any help!

2

Answers


  1. The best way is probably to use the prefers-color-scheme media feature in CSS.

    Example from
    https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme

    .day   { background: #eee; color: black; }
    .night { background: #333; color: white; }
    
    @media (prefers-color-scheme: dark) {
      .day.dark-scheme   { background:  #333; color: white; }
      .night.dark-scheme { background: black; color:  #ddd; }
    }
    
    @media (prefers-color-scheme: light) {
      .day.light-scheme   { background: white; color:  #555; }
      .night.light-scheme { background:  #eee; color: black; }
    }
    
    .day, .night {
      display: inline-block;
      padding: 1em;
      width: 7em;
      height: 2em;
      vertical-align: middle;
    }
    <div class="day">Day (initial)</div>
    <div class="day light-scheme">Day (changes in light scheme)</div>
    <div class="day dark-scheme">Day (changes in dark scheme)</div> <br>
    
    <div class="night">Night (initial)</div>
    <div class="night light-scheme">Night (changes in light scheme)</div>
    <div class="night dark-scheme">Night (changes in dark scheme)</div>
    Login or Signup to reply.
  2. You can use the built in prefers-color-scheme media feature
    It will goes with the user operating system setting (e.g. light or dark mode) or a user agent setting.
    read more about the topic

    Here’s a simple example on how to create custom style for dark mode:

    body {
      color: #000;
      background: #fff;
    }
    
    @media (prefers-color-scheme: dark) {
      body {
        color: #fff;
        background: #000;
      }
    }
    <p>
    This is a simple paragraph
    </p>

    Or you can do a custom styling without relaying on the user system preferences like the example below :

    function toggleDarkMode() {
      document.body.classList.toggle('dark');
    }
    body {
      background: white;
      color: black;
    }
    
    .dark {
      background: black;
      color: white;
    }
    <p>
    This is an example paragraph
    </p>
    <button onclick="toggleDarkMode()">Toggle dark mode</button>

    It can be improved by storing the dark mode/light mode to the localStorage

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search