Firefox Tomorrow

css pseudo class

`:focus-within` CSS pseudo-class

View on MDN ↗

The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused. 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. (This includes descendants in shadow trees.)

Interactive exampleOpen the canonical MDN source to run this embedded demo.
label {
  display: block;
  margin-top: 1em;
}

label:focus-within {
  font-weight: bold;
}
<form>
  <p>Which flavor would you like to order?</p>
  <label>Full Name: <input name="firstName" type="text" /></label>
  <label
    >Flavor:
    <select name="flavor">
      <option>Cherry</option>
      <option>Green Tea</option>
      <option>Moose Tracks</option>
      <option>Mint Chip</option>
    </select>
  </label>
</form>

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.

Syntax

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

Examples

In this example, the form will receive special coloring styles when either text input receives focus.

HTML

<p>Try typing into this form.</p>

<form>
  <label for="given_name">Given Name:</label>
  <input id="given_name" type="text" />
  <br />
  <label for="family_name">Family Name:</label>
  <input id="family_name" type="text" />
</form>

CSS

form {
  border: 1px solid;
  color: gray;
  padding: 4px;
}

form:focus-within {
  background: #ffff88;
  color: black;
}

input {
  margin: 4px;
}

Result

Interactive exampleOpen the canonical MDN source to run this embedded demo.

Specifications

SpecificationsStandards references are available on the canonical MDN page.

Browser compatibility

Browser compatibilityCompatibility data is available on the canonical MDN page.

See also