どうも、くまだです。
CSSのif()関数を使ってスタイルを変えるメモ。
if()関数
CSSのif()関数を使って、条件分岐のようにスタイルを変更できます。
コードは以下になります。
<div class="container">
<button class="box"></button>
<button class="box orange"></button>
<button class="box blue"></button>
</div>.container {
padding: 50px;
display: flex;
justify-content: center;
gap: 10px;
}
.box {
width: 100px;
height: 100px;
background-color: if(
style(--color-type:primary): orange;
style(--color-type:secondary): blue;
else: red);
}
.box.orange {
--color-type:primary;
}
.box.blue {
--color-type:secondary;
}
See the Pen if() by kuma0605 (@kuma0605) on CodePen.
以下の部分で、条件別にスタイルを指定しています。
–color-type:primaryだったら、オレンジ。
–color-type:secondaryだったら青、どちらでもなかったら赤色、という感じです。
background-color: if(
style(--color-type:primary): orange;
style(--color-type:secondary): blue;
else: red
);以下の部分で、スタイルを出しわけています。
.box.orangeの場合は、–color-type: primary;を指定してるので、上記のif()関数でいうと、style(–color-type:primary): orange;の部分が適用されます。
.box.orange {
--color-type: primary;
}
.box.blue {
--color-type: secondary;
}
.boxの場合は.orangeも.blueも指定していないので、if()関数のelse: redの部分が適用されます。
ここまで読んでくださりありがとうございました。