:focus-within
:focus-within CSS 偽類匹配元素,如果該元素或其任何後代元素獲得焦點。換句話說,它表示一個元素本身與 :focus 偽類匹配,或者其後代元素與 :focus 匹配。(這包括影子 DOM 中的後代元素。)
試一試
label {
display: block;
margin-top: 1em;
}
label:focus-within {
font-weight: bold;
}
<form>
<p>Which flavor would you like to order?</p>
<label>Full Name: <input name="firstName" type="text" /></label>
<label
>Flavor:
<select name="flavor">
<option>Cherry</option>
<option>Green Tea</option>
<option>Moose Tracks</option>
<option>Mint Chip</option>
</select>
</label>
</form>
語法
css
:focus-within {
/* ... */
}
示例
在此示例中,當任一文字輸入獲得焦點時,表單將獲得特殊的著色樣式。
HTML
html
<p>Try typing into this form.</p>
<form>
<label for="given_name">Given Name:</label>
<input id="given_name" type="text" />
<br />
<label for="family_name">Family Name:</label>
<input id="family_name" type="text" />
</form>
CSS
css
form {
border: 1px solid;
color: gray;
padding: 4px;
}
form:focus-within {
background: #ffff88;
color: black;
}
input {
margin: 4px;
}
結果
規範
| 規範 |
|---|
| 選擇器 Level 4 # the-focus-within-pseudo |
瀏覽器相容性
載入中…