:focus-within很容易让人联想到focus,区别就在于focus是对于当前元素,而:focus-within则是对于当前对象和当前对象子元素
MDN: The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus. In other words, it represents an element that is itself matched by the
:focus
pseudo-class or has a descendant that is matched by:focus
.
那么这个伪类有什么作用呢?
This selector is useful, to take a common example, for highlighting an entire form container when the user focuses on one of its input fields.
相关的例子:
<form class="user-form">
<label>账号: <input class="common-input" type="text" name="id"></label><br>
<label>密码: <input class="common-input" type="password" name="password"></label>
</form>
.user-form {
width: 300px;
height: 100px;
border: 1px solid #EDEDED;
color: #000;
padding: 4px;
}
.user-form:focus-within {
background: #EDEDED;
color: black;
}
.user-form label {
display: inline-block;
margin: 6px 10px;
}
.common-input {
margin: 4px;
}
<h2>表单输入页面</h2>
<form class="user-form">
<label>账号: <input class="common-input" type="text" name="id"></label><br>
<label>密码: <input class="common-input" type="password" name="password"></label>
</form>
.user-form {
width: 300px;
height: 100px;
border: 1px solid #EDEDED;
color: #000;
padding: 4px;
outline: 2000px solid hsla(0, 0%, 100%, 0);
transition: outline .2s;
position: relative;
z-index: 1;
}
.user-form:focus-within {
outline: 2000px solid hsla(0, 0%, 100%, 1);
}
.user-form label {
display: inline-block;
margin: 6px 10px;
}
.common-input {
margin: 4px;
}
<div class="container-textarea">
<textarea id="text" maxlength="200" rows="6"></textarea>
<label for="text" class="label-count">0/200</label>
</div>
.container-textarea {
max-width: 280px;
border: 1px solid #d0d0d5;
border-radius: 5px;
background-color: #fff;
padding-bottom: 24px;
overflow: hidden;
position: relative;
}
.label-count {
position: absolute;
font-size: 12px;
line-height: 16px;
bottom: 5px;
right: 10px;
color: #999;
}
.container-textarea textarea {
display: block;
width: 100%;
padding: 7px 9px;
border: 0;
background: none;
box-sizing: border-box;
outline: 0;
resize: none;
}
.container-textarea:focus-within {
border-color: #00a5e0;
}
当然它还是有其他应用场景的,欢迎补充^_^