--- title: ':focus-within' slug: 'Web/CSS/:focus-within' tags: - ':focus' - ':focus-within' - CSS - Layout - Pseudo-class - Reference - Selector - Web translation_of: 'Web/CSS/:focus-within' ---
CSS の :focus-within 擬似クラスは、フォーカスを持っているか、フォーカスを持った要素を含む要素を表します。言い換えれば、それ自身が {{CSSxRef(":focus")}} 擬似クラスに該当するか、子孫に :focus に該当する要素がある要素を表します。 (これはシャドウツリーにおける子孫も含みます。)
/* 子孫要素の一つにフォーカスがある <div> を選択 */
div:focus-within {
background: cyan;
}
このセレクターは、よくある例のように、 {{HTMLElement("input")}} 欄の一つにユーザーがフォーカスを置いたときに、それを含む {{HTMLElement("form")}} を強調する場合に便利です。
{{CSSSyntax}}
この例では、何れかの入力欄にフォーカスが当たった時、特殊な色のスタイルにします。
<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>
form {
border: 1px solid;
color: gray;
padding: 4px;
}
form:focus-within {
background: #ff8;
color: black;
}
input {
margin: 4px;
}
{{EmbedLiveSample("Examples", 500, 150)}}
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{SpecName("CSS4 Selectors", "#the-focus-within-pseudo", ":focus-within")}} | {{Spec2("CSS4 Selectors")}} | 初回定義 |
{{Compat("css.selectors.focus-within")}}