tutorial // Mar 15, 2024

How to Select a Previous Sibling Element With :has() in CSS

How to use the CSS :has() selector to select and style a preceding sibling HTML element.

How to Select a Previous Sibling Element With :has() in CSS

Up until recently, CSS lacked a selector for an element's preceding sibling. Now, with the :has() selector, we can access this element.

Consider the following HTML:

Example HTML

<div class="capped-input">
  <div class="input-cap">{{sDUDONzFm7LLO2YU:H33r1DNd}}lt;/div>
  <input type="number" name="amount" placeholder="Dollar Amount" />
</div>

If we want to style the .input-cap <div></div> when the input is focused, we can use :has() to target it:

Example CSS

.input-cap:has(+ input:focus) {
  background: blue;
}

Now, when the amount input is focused by the user, the background of the .input-cap element will be set to blue.

Browser Support

As of 2023, the :has() selector is considered to have baseline support across all major, modern web browsers.

Written By
Ryan Glover

Ryan Glover

CEO/CTO @ CheatCode