【CSS】ハンバーガーメニューを背景色に合わせて反転させる

前に見たとあるサイトで「メニューの色が背景色に合わせて自動で切り替わる」というのを見かけた。

ブックマークしておけば良かったのだが、忘れてた&見つからずやり方を試行錯誤したので、今度は備忘録を残しておく。

mix-blend-mode: difference;

全く知らなかったけど、mix-blend-mode というプロパティがあるらしく、それを使うことで実現した。

サンプルはこちら ↓

demo

ちなみに結局このブログでは実装しなかったので、コードだけ載せておく。

HTML

<div class="root">
  <nav>
    <button>
      <span class="top"></span>
      <span class="middle"></span>
      <span class="bottom"></span>
    </button>
  </nav>
  <section class="section1">section1</section>
  <section class="section2">section2</section>
  <section class="section3">section3</section>
  <section class="section4">section4</section>
</div>

SCSS

nav {
  mix-blend-mode: difference;
  position: fixed;
  margin-left: 85%;
  z-index: 100;
  width: 100%;
  height: 100%;
  button {
    margin-top: 10px;
    display: block;
    width: 50px;
    height: 50px;
    background-color: transparent;
    border: none;
    position: relative;
    cursor: pointer;
    outline: none;
    span {
      width: 20px;
      height: 2px;
      background-color: #fff;
      position: absolute;
      &.top {
        transform: translateY(-6px);
      }
      &.bottom {
        transform: translateY(6px);
      }
    }
  }
}

section {
  height: 100vh;
  font-size: 2rem;
  padding: 40px;
  &.section1,
  &.section3 {
    background-color: #fff;
    color: #000;
  }
  &.section2,
  &.section4 {
    background-color: #000;
    color: #fff;
  }
}
© 2022 fu9da