0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【CSS】:has()セレクター

Posted at

:has()とは

・子要素や兄弟要素などの存在や状態を条件にして、親要素にスタイルを適用できる
A:has(B) → A が B を含む場合にスタイルを適用
・:is() など他の疑似クラスと組み合わせて使える

使用例

/* input を含むラベルを太字にする */
label:has(input) {
  font-weight: bold;
}

/* チェック済みのチェックボックスを含む div の背景を赤にする */
div:has(input[type="checkbox"]:checked) {
  background: red;
}

/* h2 の直後に p がある場合だけh2を赤にする*/
h2:has(+ p) {
  color: red;
}

/* h2 の後に p が1つでもある場合だけh2を青にする*/
h2:has(~ p) {
  color: blue;
}

hasの条件に使っている

  • +は次兄弟結合子(next-sibling combinator) : 2 つ目の要素が 1 つ目の要素の直後にあって、両者が同じ親要素の子同士である場合に条件に一致する

  • ~は後続兄弟結合子(subsequent-sibling combinator): 2 つ目の要素が 1 つ目の要素の後(直後である必要はない)にあって、両者が同じ親要素の子同士である場合に条件に一致する

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?