CSS 伪选择器 focus-within 介绍

CSS中的 :focus-within 伪选择器可有点“不寻常”,尽管它的名称看上去很简单,而且相当直观。但它的解释是:选择一个包含具有:focus 的任何子元素的元素。有点绕是不是,但仔细读应该也能理解,下面通过具体的例子你就更能理解了。

form:focus-within {
  background: lightyellow;
}

它是这样工作的:

<form action="#">
  <input type="text">
</form>

当form的子元素input获得焦点时,form 就会被选中。

我说“不寻常”是因为在CSS中,根据子元素的存在或状态来选择父元素并不常见,当然也是有用的。

看下面是一个例子:

<form action="#">
  <h2>这是一个表单</h2>
  <div>
    <label class="desc" >姓名</label>
    <div>
      <input >
    </div>
  </div>
  <div>
    <label class="desc" >邮箱</label>
    <div>
      <input >
   </div>
  </div>
  <div>
    <label class="desc" >内容</label>
    <div>
      <textarea ></textarea>
    </div>
  </div>
  <div>
    <fieldset>
      <legend >请选择</legend>
      <div>
      	<input >
      	<div>
      		<input >
      		<label class="choice" for="Field5_0">First Choice</label>
      	</div>
        <div>
        	<input >
        	<label class="choice" for="Field5_1">Second Choice</label>
        </div>
      </div>
    </fieldset>
  </div>
  <div>
    <fieldset>
      <legend >请选择</legend>
      <div>
      <div>
      	<input >
      	<label class="choice" for="Field6">First Choice</label>
      </div>
      <div>
      	<input >
      	<label class="choice" for="Field7">Second Choice</label>
      </div>
    </fieldset>
  </div>
  <div>
    <label class="desc" >请选择</label>
    <div>
    <select >
      <option value="First Choice">First Choice</option>
      <option value="Second Choice">Second Choice</option>
    </select>
    </div>
  </div>
</form>
form:focus-within {
  background: #f9f98b;
}
form header {
  padding: 2rem;
}
form header div {
  font-size: 90%;
  color: #999;
}
form header h2 {
  margin: 0 0 5px 0;
}
form > div {
  clear: both;
  overflow: hidden;
  padding: 0.5rem 2rem;
}
form > div:last-child {
  padding-bottom: 2rem;
}
form > div:focus-within {
  background: #a1c084;
}
form > div > fieldset > div > div {
  margin: 0 0 5px 0;
}
form > div > label,
legend {
	 15%;
  float: left;
  padding-right: 10px;
}
form > div > div,
form > div > fieldset > div {
   85%;
  float: right;
}
form > div > fieldset label {
	font-size: 90%;
}
fieldset {
	border: 0;
  padding: 0;
}

input[type=text],
input[type=email],
input[type=url],
input[type=password],
textarea {
	 100%;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #eee;
  border-bottom: 1px solid #eee;
}
input[type=text],
input[type=email],
input[type=url],
input[type=password] {
   50%;
}
input[type=text]:focus,
input[type=email]:focus,
input[type=url]:focus,
input[type=password]:focus,
textarea:focus {
  outline: 0;
  border-color: #4697e4;
}

效果图:

CSS 伪选择器 focus-within 介绍

注意上面的示例在整个表单和其内部的div上使用了:focus-within。子元素通过任意方式获得焦点都将触发:focus-within。例如,如果一个元素有tab-index属性或contenteditable属性时,那么它就是一个可聚焦的元素。元素如何成为焦点也不重要,它可以被点击或轻触,或通过其他方式导航,甚至通过JavaScript聚焦,比如:

document.querySelector("input").focus();

下面是:focus-within在各大浏览器上的支持情况:

CSS 伪选择器 focus-within 介绍

可见截止目前大部门主流浏览器都已经支持了。