みかづきブログ・カスタム

基本的にはちょちょいのほいです。

CSSでダークモードを判定する 🐦‍⬛

developer.mozilla.org

OSのダークモードですが、メディアクエリで簡単に判定できます。

@media (prefers-color-scheme: dark) {
  /* ダークモードのスタイルを書く */
}

DEMO

最近つくっている、PWAをホーム画面に登録することを促すポップアップです。
ライトモードとダークモードでデザインを変えてみました。


ソースコード

index.scss

@keyframes flow {
  0%   {
    bottom: 20px;
  }
  50%  {
    bottom: 40px;
  }
  100% {
    bottom: 20px;
  }
}

.balloon {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  bottom: 20px;
  left: 0; right: 0;
  margin: auto;
  border-radius: 60px;
  width: 140px; height: 140px;
  font-size: 10px;
  text-align: center;
  letter-spacing: .2em;
  background: #eee;
  animation: flow 2s ease 0s infinite normal;
  box-shadow: 0 0 5px rgba(0, 0, 0, .2);

  @media (prefers-color-scheme: dark) {
    background: #3d3d3d;
  }

  .download-icon {
    margin: auto;
  }

  .store-balloon-text {
    margin-top: 8px;
    color: #000;
    line-height: 1.4em;

    @media (prefers-color-scheme: dark) {
      color: #fefefe;
    }
  }

  &:after {
    display: block;
    position: absolute;
    margin-left: -10px;
    bottom: -20px; left: 50%;
    width: 0; height: 0;
    border: solid transparent 10px;
    border-top: solid #eee 10px;
    content: '';

    @media (prefers-color-scheme: dark) {
      border-top-color: #3d3d3d;
    }
  }
}

.download-icon {
  display: block;
  position: relative;
  border: solid 2px #000;
  border-radius: 6px;
  width: 30px; height: 30px;

  @media (prefers-color-scheme: dark) {
    border-color: #fefefe;
  }

  &:before {
    display: block;
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;
    border-radius: 1px;
    width: 15px; height: 2px;
    content: '';
    background: #000;

    @media (prefers-color-scheme: dark) {
      background: #fefefe;
    }
  }

  &:after {
    display: block;
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;
    border-radius: 1px;
    width: 2px; height: 15px;
    content: '';
    background: #000;

    @media (prefers-color-scheme: dark) {
      background: #fefefe;
    }
  }
}

** index.html

>|html|
<div class="balloon">
  <div>
    <span class="download-icon"></span>
    <p class="store-balloon-text">ホーム画面に<br>追加</p>
  </div>
</div>