Lớp giả CSS :focus-within
đại diện cho thành phần nhận focus hoặc chứa một thành phần nhận focus. Nói cách khác, nó đại diện cho một thành phần mà chính nó khớp bởi một lớp giả :focus
hoặc có một hậu duệ (con cháu) được khớp bởi :focus
. (Gồm cả hậu duệ trong shadow trees.)
/* Chọn một <div> khi hậu duệ của nó được focus */
div:focus-within {
background: cyan;
}
Nó rất hữu dụng, ví dụ chung, để làm nổi bật toàn bộ container <form>
khi người dùng focus vào một trong các field <input>
của nó.
Cú pháp
:focus-within
Ví dụ
Trong ví dụ này, form sẽ nhận kiểu màu đặc biệt khi text input nhận focus.
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
form {
border: 1px solid;
color: gray;
padding: 4px;
}
form:focus-within {
background: #ff8;
color: black;
}
input {
margin: 4px;
}
Result
Chi tiết
Chi tiết | Tình trạng | Comment |
---|---|---|
Selectors Level 4 The definition of ':focus-within' in that specification. |
Working Draft | Initial definition. |
Tương thích Trình duyệt
BCD tables only load in the browser