2
1

More than 1 year has passed since last update.

CSSの擬似クラス:has()を使ってみる

Last updated at Posted at 2022-12-21

ひとりCSS Advent Calendar 2022 22日目です。

:has() 使ってみます

:has() とは

()の中のセレクターを持っている要素にスタイルを当てられる。

サンプル

サンプル1

p 要素がすぐ下にある h2 はオレンジ色にする。

image.png

<section>
  <h2>Headline</h2>
  <p>Paragraph</p>
</section>
<section>
  <h2>Headline</h2>
  <div><p>div > Paragraph</p></div>
</section>
:root {
  --color1: #edb658;
}

h2:has(+ p) {
  color: var(--color1);
}

サンプル2

p 要素を持たない section 要素は中央揃えにする。

image.png

<section>
  <h2>Headline</h2>
</section>
<section>
  <h2>Headline</h2>
  <p>Paragraph<br>Paragraph<br>Paragraph<br>Paragraph</p>
</section>
section:not(:has(p)) {
  text-align: center;
}

感想

  • 〇〇を持っている要素や、〇〇の上にある要素に対して指定できるようになったのとてもありがたい…

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1