There’s been a lot of hype lately around the CSS :has() pseudo-class. And rightly so! It’s basically the “parent selector” we’ve been asking for for years. Today I want to focus on ways we can use :has() to make HTML forms even better.
(There’s a Codepen demo at the end)
Preface
In this article I’ll be working with custom form controls that look like this:
<div class="control">
<label for="name">Name</label>
<div class="control__input">
<input type="text" id="name" name="name" required>
</div>
</div>A <div> wrapping the whole control, a <label> to keep the input accessible, a wrapper <div> around the input element, and the <input> element itself. The input element will have no border or background. The “control__input” <div> will have the styling to serve as the visual representation of the form control.
.control :where(input, select, textarea) {
border: 0;
background-color: transparent;
}
.control__input {
display: flex;
align-items: center;
gap: .125rem;
border: .125rem solid;
border-radius: .25rem;
padding: .25rem;
}