Other

Dark theme toggle

20 Sep 2022

Dark theme toggle
HTML
SCSS
PostCSS
JS
                            <label class="header__theme-selector">
  <input type="checkbox" />
  <div class="header__theme-highliter"></div>
  <div class="header__theme-variant" id="day">
    <i class="icon-sun-dim"></i>
  </div>
  <div class="header__theme-variant" id="night">
    <i class="icon-moon"></i>
  </div>
</label>
                        
                            /* variables */
:root {
  --bg-main-cl-light: #f9f9fa;
  --bg-main-cl-dark: #2a2a2a;

  --text-cl-light: #484854;
  --text-cl-dark: #adadb5;
}

:root {
  --bg-main-cl: var(--bg-main-cl-light);
  --text-cl: var(--text-cl-light);
}

.dark {
  --bg-main-cl: var(--bg-main-cl-dark);
  --text-cl: var(--text-cl-dark);
}

.header__theme-selector {
  position: relative;

  display: flex;

  padding: 3px;
  border-radius: 7px;

  background-color: var(--light-gray);

  cursor: pointer;

  input {
    position: absolute;
    visibility: hidden;
    width: 1px;
    height: 1px;

    &:checked ~ #day {
      color: var(--text-cl);
    }

    &:checked ~ #night {
      color: var(--white);
    }

    &:checked ~ .header__theme-highliter {
      transform: translate(100%, -50%);
    }
  }
}
                        
                            /* _variables.pcss */
:root {
  --bg-main-cl-light: #f9f9fa;
  --bg-main-cl-dark: #2a2a2a;

  --text-cl-light: #484854;
  --text-cl-dark: #adadb5;
}

:root {
  --bg-main-cl: var(--bg-main-cl-light);
  --text-cl: var(--text-cl-light);
}

.dark {
  --bg-main-cl: var(--bg-main-cl-dark);
  --text-cl: var(--text-cl-dark);
}

/* _header-footer.pcss */
.header__theme-selector {
  position: relative;

  display: flex;

  padding: 3px;
  border-radius: 7px;

  background-color: var(--light-gray);

  cursor: pointer;

  input {
    position: absolute;
    visibility: hidden;
    width: 1px;
    height: 1px;

    &:checked ~ #day {
      color: var(--text-cl);
    }

    &:checked ~ #night {
      color: var(--white);
    }

    &:checked ~ .header__theme-highliter {
      transform: translate(100%, -50%);
    }
  }
}
                        
                            <script>
  (() => {
    const ls = localStorage.getItem("theme");
    const theme = window.matchMedia("(prefers-color-scheme: dark)").matches;
    if (ls === "dark") {
      document.documentElement.classList.add("dark");
    } else if (!ls && theme) {
      document.documentElement.classList.add("dark");
    }
  })();
</script>
                        

JS код вставляти в head тег для кращої роботи.

0