1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

hasセレクタでダークモード切り替え

Last updated at Posted at 2025-07-24

HTMLにラジオボタンやチェックボックスを設置して、
CSSに {{スタイルを切り替えたい要素}}:has({{ラジオボタン}}:checked) { ~ } を記述すれば、
あら不思議、JS要らずでお手軽にスタイルを切り替えられます。

フォントサイズ変更や ダークモード切替だって これでバッチリ。


HTML: 🌞 🌛
<body>
  <lebel>
    <input type="radio" name="mode" value="day" checked>
    <span>🌞</span>
  </lebel>
  <lebel>
    <input type="radio" name="mode" value="night">
    <span>🌛</span>
  </lebel>
</body>
CSS: 🌞 🌛
body {

  /* 🌞 選択中の色を指定する */
  &:has(input[name="mode"][value="day"]:checked) {
    color: black;
    background-color: white;
  }

  /* 🌛 選択中の色を指定する */
  &:has(input[name="mode"][value="night"]:checked) {
    color: white;
    background-color: white;
  }
}

以下は light-dark() を交えた例。

CSS: 🌞 🌛
/* 環境によってはこのブロックは不要みたい。
:root {
  color-scheme: light dark;
}
*/

body {

  /* lightモード時とdarkモード時の色を指定する */
  color: light-dark(black, white);
  background-color: light-dark(white, black);

  /* 🌞 選択中はlightモードにする */
  &:has(input[name="mode"][value="day"]:checked) {
    color-scheme: light;
  }

  /* 🌛 選択中はdarkモードにする */
  &:has(input[name="mode"][value="night"]:checked) {
    color-scheme: dark;
  }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?