其实就是一个新的媒体查询啦

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>dark-light</title>
    <style>
      .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;
      }
    </style>
  </head>
  <body>
    <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>
  </body>
</html>

在这里手动切换查看效果:

t0128ff51237b095671

可以看到是实时的(不用刷新网页):(gif 1m比较大,加载比较慢)

t012a784818649249bd

兼容性:

t017df6dab24fd5504b

可以看到,基本上只有比较新的浏览器才支持这个特性。不过这些浏览器厂商还是狠啊,很多特性标准还在w3c草案阶段,那边已经实现了,确实有点屌 😆

t013399f901078aa026

相关链接: