: focus within is easy to associate with focus. The difference is that focus is for the current element, while: focus within is for the current object and its child elements
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
.
So what does this pseudo class do?
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.
Related examples:
Highlight the background when the form interacts
<form class="user-form">
<label>Account number: <input class="common-input" type="text" name="id"></label><br>
<label>Password: <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;
}
When the form is input, other elements of the form are not visible
<h2>Form input page</h2>
<form class="user-form">
<label>Account number: <input class="common-input" type="text" name="id"></label><br>
<label>Password: <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;
}
Highlight text field with count
<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;
}
Of course, it has other application scenarios. Please add^_^