どのように設定するには、ライト/ダークモードのユーザーの設定に応じて!


多くのウェブサイトは、ユーザが自分の光と暗いモードを切り替えることができるヘッダーのトグルを持っています.これは素晴らしい機能ですが、彼らはすでにオペレーティングシステムの設定で自分の好みを設定するチャンスがあります.あなたのウェブサイトが単に彼らのセッティングに従って敏感であるならば、それは素晴らしいことでありませんか?
これはCSSでprefers-color-schemeメディアクエリで可能です!

どのように、プレハブカラー計画は働きますか?

prefers-color-schemeは他の@mediaのクエリとまったく同じように機能します.
基本的な例
@media (prefers-color-scheme: light) {
  body{
      /* Set the background to white and text to black */
      background: white;
      color: black;
  }
}

@media (prefers-color-scheme: dark) {
  body{
      /* Set the background to black and text to white */
      background: black;
      color: white;
  }
}
ちょうどそのように、あなたのウェブサイトは、ユーザーの好みに変更に応答します.
ライブデモのために、see this example on CodePen .あなたのオペレーティングシステムの設定をライトモードからダークモードとその逆に設定し、ページを動的に変更色をチェック!

ベストプラクティス


上のコード例ではlightdarkの両方を使用する方法を示しました.しかし、いくつかのオペレーティングシステムはカラースキームをサポートしません、あるいは、古いブラウザはprefers-color-schemeをサポートしません.解決策はprefers-color-schemeなしでデフォルトの色を設定し、後に別のカラースキームを設定することです.
例えば、
/* The light mode is set as default here without the `prefers-color-scheme` query.
This will be set if the query isn't supported for whatever reason. */

body{
    background: white;
    color: black;
}

/* This will be taken into account only if colour scheme preference is supported by the operating system or browser.
It will set the page to dark if the colour preference is set to dark. */
@media (prefers-color-scheme: dark) {
  body{
      background: black;
      color: white;
  }
}