:focus-within伪类选择器的3种应用

时间:2024-09-27 12:34:08

1.点击form里任意input隐藏form以外内容提高用户体验

<form><input type="text"></form>
form {
transition: outline .2s;
outline: 2000px solid hsla(0,0%,100%,0);
position: relative;
z-index:;
}
form:focus-within {
outline: 2000px solid hsla(0,0%,100%,1);
}

2.解决带计数文本域自身:focus高亮重叠问题

<div class="textarea-x">
<textarea id="forFocus" maxlength="250" rows="5"></textarea>
<label for="forFocus" class="textarea-count">0/250</label>
</div>
.textarea-x {
max-width: 298px;
border: 1px solid #d0d0d5;
border-radius: 4px;
background-color: #fff;
padding-bottom: 24px;
transition: border-color .2s;
overflow: hidden;
position: relative;
}
.textarea-count {
position: absolute;
font-size: 12px;
line-height: 16px;
bottom: 5px; right: 10px;
color: #999;
}
.textarea-x > textarea {
display: block;
width: 100%;
padding: 7px 9px;
border:;
background: none;
-ms-box-sizing: border-box;
box-sizing: border-box;
outline:;
resize: none;
}
.textarea-x:focus-within {
border-color: #00a5e0;
}

3.纯css实现下拉

<div class="details">
<a href="javascript:">我的消息</a>
<div class="box">
<li>1</li>
<li>2</li>
<li>3</li>
</div>
</div>
.box {
display: none;
}
.details:focus-within .box {
display: block;
}

:focus跟:focus-within的区别在于前者表示当前元素处于focus状态时,后者是当前元素或者当前元素的子元素处于focus状态时。