1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CSSで兄弟を指定する方法メモ

Last updated at Posted at 2022-12-21

動機

CSSの仕様 には兄弟を指定するための構文として一般兄弟結合子(~)、隣接兄弟結合子(+)が定義されているものの、これで対象となるのは弟妹のみであって、兄姉を直接指定する方法は用意されていない.
:has() 疑似クラスを使用すれば兄姉を指定できるのだがパッと思いつかなかったりする.
なのでここにメモしておく.
ただし、:has() 疑似クラスが古いブラウザで動作しない点は注意.

環境

Google Chrome バージョン: 108.0.5359.125 で動作することを確認

具体例

HTML

具体例
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>Test CSS</title>
  <style>
    .me::after {
	  content: " [This is me!]";
	}
    .me + .sibling::after {
	  content: " [ひとつ弟]";
	}
    .me + .sibling + .sibling::before {
	  content: "[ふたつ弟] ";
	}
    .sibling:has(+ .me)::after {
	  content: " [ひとつ兄]";
	}
	/* :has(*) は入れ子にできないので、ふたつ兄を指定するためには使えない
     * ∴ [.sibling:has(+ .sibling:has(+ .me))::before] は不正
	 * ふたつ兄を指定するためには入れ子にせず指定する
	 */
    .sibling:has(+ .sibling + .me)::before {
	  content: "[ふたつ兄] ";
	}
	/* 弟妹全員 */
    .me ~ .sibling {
	  color: red;
	}
	/* 兄姉全員 */
    .sibling:has(~ .me) {
	  color: blue;
	}
	/* 兄弟全員 :not(.me) を取り除けば .me も対象となる */
    *:has(> .me) > .sibling:not(.me) {
	  background-color: yellow;
	}
  </style>
</head>
<body>
  <ul>
    <li class="sibling">First
    <li class="sibling">Second
    <li class="sibling">Third
    <li class="sibling me">Forth
    <li class="sibling">Fifth
    <li class="sibling">Sixth
    <li class="sibling">Seventh
  <ul>
</body>
</html>

SS

Chromeでの表示.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?