意外と知られていないCSSの:is()擬似クラス関数の使い方

:is()擬似クラス関数とは

CSSの:is()を使えばセレクターのリストを引数に入れて要素を選択することができる。

例えばsection直下のh1, h2, h3のテキスト色を緑にする場合は下記のように書かれることが多いが…

section > h1,
section > h2,
section > h3 {
  display: inline;
  color: green;
}

:is()を使用すれば短く記述できる。

section > :is(h1, h2, h3) {
  display: inline;
  color: green;
}
<section>
  <h1>foo</h1>
  <h2>bar</h2>
  <h3>baz</h3>
</section>

foo

bar

baz

:is()は組み合わせて使用可能

:is() > :is() のような形でも使用できるため以下のようなコードも適用できる。

:is(.foo, .bar) > :is(h1, h2, h3) {
  display: inline;
  color: skyblue;
}
<div class="foo">
  <h1>foo</h1>
  <h2>bar</h2>
  <h3>baz</h3>
</div>
<div class="bar">
  <h1>foo</h1>
  <h2>bar</h2>
  <h3>baz</h3>
</div>

foo

bar

baz

foo

bar

baz

:is()は:hoverや:focusにも使用可能

:is()は:hoverや:focusにも使用できるので以下のように短縮することもできる。

.test input:is(:hover, :focus) {
  background: lightgreen;
}
<div class="test">
  <input type="text">
</div>

:not()で:is()を逆転可能

:not()に:is()を入れて指定すれば他の擬似クラスと同様に指定内容を逆転できる。

.test2 input:not(:is(:hover, :focus)) {
  background: lightgreen;
}
<div class="test2">
  <input type="text">
</div>

CSSセレクタの優先順位は:is()でも同じ

:is()に書き換えたたとしてもCSSセレクタの優先順位は変わらない。

そのため、以下の記述は「赤」となり、

.foo > .bar,
.foo > .baz {
  color: green;
}

.foo > :is(.bar, .baz) {
  color: red;
}

以下の記述は「緑」となる。

.foo > :is(.bar, .baz) {
  color: red;
}

.foo > .bar,
.foo > .baz {
  color: green;
}
<div class="foo">
  <div class="bar">bar</div>
  <div class="baz">baz</div>
</div>
bar
baz
カテゴリーcss