Amit is an experienced web developer who mainly does front-end, specializing in CSS, animations, and creative coding. Over the years, he’s taken par

Combining CSS :has() And HTML <select> For Greater Conditional Styling

submited by
Style Pass
2024-05-02 16:00:05

Amit is an experienced web developer who mainly does front-end, specializing in CSS, animations, and creative coding. Over the years, he’s taken part in … More about Amit ↬

Even though the CSS :has() pseudo-class is relatively new, we already know a lot about it, thanks to many, many articles and tutorials demonstrating its powerful ability to conditionally select elements based on their contents. We’ve all seen the card component and header examples, but the conditional nature of :has() actually makes it adept at working with form controls, which are pretty conditional in nature as well.

Let’s look specifically at the <select> element. With it, we can make a choice from a series of <option>s. Combined with :has(), we are capable of manipulating styles based on the selected <option>.

This is your standard <select> usage, producing a dropdown menu that contains options for user selection. And while it’s not mandatory, I’ve added the selected attribute to the first <option> to set it as the initial selected option.

Leave a Comment