Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readCSS

Style parents with :has()

Use a CSS :has() selector with :user-invalid to highlight a field group after a failed validation attempt.

Your email input gets an error border, but the label above it still looks like the rest of the form. You want a border around the field group, so the error marker sits next to both the label and the input.

Match the field group

Give each field its own wrapper. Then match the wrapper with .field:has(> input:user-invalid). The direct-child combinator keeps the rule scoped to the input that belongs to this wrapper.

Save this as form.html and open it in a browser.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Field group validation</title>
<style>
  .field {
    max-width: 22rem;
    margin-block: 0.5rem;
    padding: 0.75rem;
    border-inline-start: 0.25rem solid transparent;
  }
  .field:has(> input:user-invalid) {
    border-inline-start-color: #b42318;
    font-weight: bold;
  }
</style>
<form>
  <div class="field">
    <label for="email">Email</label>
    <input id="email" name="email" type="email" required>
  </div>
  <div class="field">
    <label for="alias">Display name</label>
    <input id="alias" name="alias">
  </div>
  <button>Save</button>
</form>
</html>

On load, both borders are transparent. Press Save with a blank email and the email group gets a red border and a bold label. Type ada@example.com into Email. The group returns to its original style once the address passes validation.

Read the rule from the outside in. CSS applies the declarations to .field when :has() finds a matching direct child. The input supplies the condition and the group owns the border. If the display name gets another validation rule later, it can trigger its own border without colouring the email group.

Choose when the condition matches

A blank required input matches :invalid on page load. To give the reader a chance to fill it in, the example uses :user-invalid. An attempted submission makes the blank required email show its error even when the reader skipped the field.

The browser still supplies the validation message through the native form. Treat the border as an extra visual cue. If you replace native validation with your own checks, put the reason for the error in text and associate it with the control.

Check the wrapper if the border stays clear

Open the Elements panel and look at the input’s immediate parent. If a component library wraps the input in another element, the > selector can no longer reach it. Move the class to the immediate wrapper or match the actual chain, such as .field:has(> .control > input:user-invalid).