【PR】お得なのに速くて使いやすい「シンレンタルサーバー」

簡単なダークモード用トグルボタンの実装メモ

簡単なダークモードトグルボタンのメモです。

See the Pen toggle-button by hiro (@hirochanpon) on CodePen.

HTML

<button class="git-theme-toggle" id="gitThemeToggle" aria-label="Toggle dark mode">
  <span class="icon">◐</span>
</button>

CSS

/* ボタン本体 */
.git-theme-toggle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 34px;
  height: 34px;
  border: 0px solid #d0d7de;
  border-radius: 4px;
  background: transparent;
  color: #24292f;
  cursor: pointer;
  padding: 0;
}

/* アイコン */
.git-theme-toggle .icon {
  font-size: 26px;
  line-height: 1;
}

/* hover */
.git-theme-toggle:hover {
  border-color: #f14e32;
}

/* ダークモード時 */
html.theme-dark .git-theme-toggle {
  background:transparent;
  border-color: #30363d;
  color: #c9d1d9;
}

JS

<script>
(function () {
  const toggle = document.getElementById('gitThemeToggle');
  const root = document.documentElement;
  const storageKey = 'theme-mode';

  // 初期状態
  if (localStorage.getItem(storageKey) === 'dark') {
    root.classList.add('theme-dark');
  }

  if (!toggle) return;

  toggle.addEventListener('click', function () {
    const isDark = root.classList.toggle('theme-dark');
    localStorage.setItem(storageKey, isDark ? 'dark' : 'light');
  });
})();
</script>

スイッチで.theme-darkを付与しますので、それに合わせてCSSを書けばダークモード実装できます。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!
プロフィールアイコン
           
hirochanpon
           

ブログカスタマイズが趣味で夜な夜なサイト作成の勉強をしています。小3育児中の主婦。            

目次