:focus-within

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

:focus-withinCSS擬似クラスで、その要素または子孫要素にフォーカスがある場合に一致します。言い換えれば、それ自身が :focus 擬似クラスに該当するか、子孫に :focus に該当する要素がある要素を表します。(これはシャドウツリーにおける子孫も含みます。)

試してみましょう

このセレクターは、よくある例のように、 <input> 欄の一つにユーザーがフォーカスを置いたときに、それを含む <form> 全体を強調する場合に便利です。

構文

css
:focus-within {
  /* ... */
}

この例では、何れかの入力欄にフォーカスが当たった時、特殊な色のスタイルにします。

HTML

html
<p>このフォームに入力してみてください。</p>

<form>
  <label for="given_name">名前:</label>
  <input id="given_name" type="text" />
  <br />
  <label for="family_name">苗字:</label>
  <input id="family_name" type="text" />
</form>

CSS

css
form {
  border: 1px solid;
  color: gray;
  padding: 4px;
}

form:focus-within {
  background: #ff8;
  color: black;
}

input {
  margin: 4px;
}

結果

仕様書

Specification
Selectors Level 4
# the-focus-within-pseudo

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:focus-within

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報