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?

More than 1 year has passed since last update.

CSS Selectors Level 4 後半

Posted at

CSS Selectors Level 4について

:scope

:scopeは現在のスコープ内でマッチする要素を指定するための擬似クラス
通常JavaScriptで作成されたシャドウDOMに使用します

例えば、以下のようなHTMLがある場合

<div id="example">
  <h1>Example</h1>
  <p>Some text here.</p>
</div>
#example h1 {
  color: red;
}

JavaScriptを使用して#example要素内にシャドウDOMを作成し、h1要素を含める場合、上記のCSSではh1要素に適用されない
これを回避するために:scopeを使用してスコープ内で要素を選択する

const shadowRoot = document.getElementById('example').attachShadow({mode: 'open'});
shadowRoot.innerHTML = `
  <h1>Example</h1>
  <p>Some text here.</p>
`;
#example :scope h1 {
  color: red;
}

:focus-visible

:focus-visibleは要素がフォーカスを受け取っている場合にスタイルを適用するためのCSS擬似クラス
:focusと似ているが:focus-visibleは要素がキーボード以外の入力方法によってフォーカスを受け取った場合は適用されない

タブキーを使用してフォーカスを移動した場合にのみスタイルを適用したい場合は:focus-visibleを使用する

input:focus-visible {
  box-shadow: 0 0 0 3px rgba(0, 0, 255, 0.5);
}

:focus-within

:focus-withinは要素内の子孫要素がフォーカスされた時にスタイルを適用するための疑似クラス

<div class="container">
  <label for="input">Name:</label>
  <input id="input" type="text" name="name">
</div>
.container:focus-within {
  border: 1px solid blue;
}

この場合、子要素であるinputがフォーカスされた時にdiv.containerにborder: 1px solid blueのスタイルが適用される

また、以下のようにinputにフォーカス時に別の子要素にスタイルを当てる使い方も可能

<div class="container">
  <label for="input">Name:</label>
  <input id="input" type="text" name="name">
</div>
.container:focus-within label {
  border: 1px solid blue;
}

:has()

指定したセレクタを内包する要素にスタイルを適用

div:has(p) {
  background-color: yellow;
}

子要素にpを持つdivに対し黄色の背景色を付けるという意味になる

div:has(:not(p)) {
  background-color: yellow;
}

逆にpを持たない(p以外の何かを持つ)divに対してスタイルを適用できる
組み合わせにより複雑な設定も可能

:lang()

:lang()は要素の言語属性に基づいてスタイルを適用するための擬似クラス
<p lang="en"><p lang="ja">で異なるlang設定されている場合にそれぞれスタイルを適用することが可能

p:lang(ja) {
  color: red;
}

p:lang(en) {
  color: blue;
}

前方一致・後方一致の設定方法について

:lang(ja)はlang="ja"だけでなく、lang="ja-JP"やlang="ja-Hira"などの要素にもスタイルを適用

:lang(|-ja)はlang="ja"だけでなく、lang="en-US-ja"やlang="zh-TW-Hant-ja" などの要素にもスタイルを適用

:lang(ja) {
  color: red;
}
:lang(|-ja) {
  color: red;
}
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?