≪ Today I learned. RSS購読
公開日
更新日
タグ
CSS
著者
ダーシノ(@bc_rikko)

CSSでif()が使えるようになる

Inline conditionals(if())が CSS Values Module Level 5 の仕様に追加される。

@supportsstyle(--variable, val)のような分岐をブロックにわけず書けるようになるので、スコープが狭くなり可読性が向上する。

Before

.class {
  prop: xxx;
}
@supports (...) {
  .class {
    prop: yyy;
  }
}

After

.class {
  prop: if(supports(...), xxx, yyy);
}

追記: 2025-05-14

Chrome 137 Betaif()が実装された。

また、CSS Values and Units Module Level 5の仕様も少し変わった。

<if()> = if( [ <if-condition> : <declaration-value>? ; ]*
             <if-condition> : <declaration-value>? ;? )
<if-condition> = <boolean-expr[ <if-test> ]> | else
<if-test> =
  supports( [ <supports-condition> | <ident> : <declaration-value> ] ) |
  media( <media-query> ) |
  style( <style-query> )

つまりif(condition: value1; else: value2);という書き方になった。

.container {
  color: if(style(--theme: dark): white; else: black);
}

.container {
  display: if(supports(display: grid): grid; else: block);
}

.container {
  background-color: if(
    media(min-width: 1024px): red;
    media(min-width: 768px): blue;
    else: green;
  );
}

デモ

—theme: dark

—theme: light

if()のデモ