CSS - :focus-within伪类



CSS 中的:focus-within伪类选择器用于选择包含获得焦点的元素(:focus)的元素。

例如,如果您想在将焦点设置在任何输入字段上时突出显示或聚焦整个表单,请使用伪类:focus-within

语法

:focus-within {
   /* ... */
}

CSS :focus-within 示例

以下示例演示了:focus-within伪类的用法。当焦点设置在输入字段上时,该输入字段的标签会被突出显示。

<html>
<head>
<style>
    label {
        display: block;
        font-size: 20px;
        color: black;
        width: 500px;
    }

    input[type="text"] {
        padding: 10px 16px;
        font-size: 16px;
        color: black;
        background-color: #fff;
        border: 1px solid #597183;
        border-radius: 8px;
        margin-top: 5px;
        width: 500px;
        transition: all 0.3s ease;
    }

    input[type="text"]:focus {
        background-color: lightyellow;
    }

    label:focus-within {
        font-size: 25px;
        color: red;
    }
</style>
</head>
<body>
    <form>
        <label>
        Full Name
        <input type="text">
        </label>
    </form>
</body>
</html>

以下示例演示了:focus-within伪类的用法。当焦点设置在下拉菜单上时,会改变标签的背景和边框。

<html>
<head>
<style>
   label {
      display: grid;
      font-size: 18px;
      color: black;
      width: 400px;
   }

   select {
      padding: 10px 16px;
      font-size: 16px;
      color: black;
      background-color: #fff;
      border: 1px solid #597183;
      border-radius: 8px;
      margin-top: 25px;
      width: 300px;
      transition: all 0.3s ease;
   }

   select:focus {
      background-color: rgb(173, 233, 209);
   }

   label:focus-within {
      background-color: coral;
      border: 2px dashed black;
   }
</style>
</head>
<body>
   <form>
      <label>
         Ice cream Flavors:
         <select name="flavor">
            <option>Cookie dough</option>
            <option>Pistachio</option>
            <option>Cookies & Cream</option>
            <option>Cotton Candy</option>
            <option>Lemon & Raspberry Sorbet</option>
          </select>
      </label>
   </form>
      </label>
   </form>
</body>
</html>
广告