web制作において、ハンバーガーメニューなどのオブジェクトや文字の色を反転させたい場面が多々あると思います。
色の反転をさせることで、背景色と被る事がなくなり、文字やオブジェクトの視認性が抜群に上がります。
ただ、CSSで色の反転って難しそうと思っている方もいるかと思います。
安心してください。
今回は、CSSをたった1行書くだけで、簡単に色を反転させる方法についてご紹介します。
Contents
結論から先にいいます。
色を反転させるためには、反転させたい文字やオブジェクトに
mix-blend-mode: difference;
上記のCSSを追加するだけです。
mix-blend-modeは、要素の内容物と要素の背景をどのように組み合わせるかを設定する、CSSのプロパティです。
mix-blend-modeは他にも様々な値が用意されています。
mix-blend-mode: normal;
mix-blend-mode: multiply;
mix-blend-mode: screen;
mix-blend-mode: overlay;
mix-blend-mode: darken;
mix-blend-mode: lighten;
mix-blend-mode: color-dodge;
mix-blend-mode: color-burn;
mix-blend-mode: hard-light;
mix-blend-mode: soft-light;
mix-blend-mode: difference;
mix-blend-mode: exclusion;
mix-blend-mode: hue;
mix-blend-mode: saturation;
mix-blend-mode: color;
mix-blend-mode: luminosity;
See the Pen 反転1 by 古澤 良汰 (@ryotarofu) on CodePen.
<div class="scroll">
<p class="text">text</p>
<div class="color black"></div>
<div class="color gray"></div>
<div class="color white"></div>
<div class="color blue"></div>
<div class="color red"></div>
</div>
.scroll{
margin-top: 200px;
overflow-y: scroll;
height: 200px;
}
.text{
position: fixed;
left: 41%;
margin-top: 65px;
font-size: 50px;
color: #fff;
mix-blend-mode: difference;
}
.color{
height: 200px;
}
.black{
background-color: #000;
}
.gray{
background-color: #555;
}
.white{
background-color: #fff;
}
.blue{
background-color: blue;
}
.red{
background-color: red;
}
See the Pen 反転2 by 古澤 良汰 (@ryotarofu) on CodePen.
<div class="scroll">
<div class="box"></div>
<div class="color black"></div>
<div class="color gray"></div>
<div class="color white"></div>
<div class="color blue"></div>
<div class="color red"></div>
</div>
.scroll{
overflow-y: scroll;
height: 200px;
}
.box{
position: fixed;
width:50px;
height: 50px;
left: 47%;
margin-top: 75px;
background-color: #fff;
mix-blend-mode: difference;
}
.color{
height: 200px;
}
.black{
background-color: #000;
}
.gray{
background-color: #555;
}
.white{
background-color: #fff;
}
.blue{
background-color: blue;
}
.red{
background-color: red;
}
オブジェクトと文字に共通するポイントとして、どちらも色を「white(#fff)」に設定しています。
文字の方ではカラーを、オブジェクトの方では背景色をホワイトにしています。
ホワイトにすることで、反転させたあとの色の見え方がきれいになります。
是非活用してみてください。