CSS - Pseudo-class :focus-within



The :focus-within pseudo-class selector in CSS selects an element, if it contains an element that has recieved the focus (:focus).

For example, if you want to highlight or focus a complete form, when focus is set on any of the input fields, use the pseudo-class :focus-within.

Syntax

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

CSS :focus-within Example

Following example demonstrates the use of :focus-within pseudo-clas. When the focus is set on an input field, label of that input field is highlighted.

<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>

Following example demonstrates the use of :focus-within pseudo-clas. When the focus is set on a dropdown, in turn changes the background and border of the label.

<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>
Advertisements