Finally, :has() is here!

Long overdue, but we finally get to play with the :has() selector thanks to the latest version of Safari Technology Preview 137

Week 220 was posted by Charanjit Chana on 2022-01-10.

After what feels like an eternity, CSS finally has a parent selector and you can play with it in Safari Technology Preview 137.

I wrote about how excited I was a few months ago and that hasn't depended at all. With more examples I've stumbled across I get why this selector is called 'has' rather than 'contains' or 'parent', it really does do much more than signify that one item is the parent of another.

label:has(+ input) { // css goes here }

In this scenario it will check the label is followed by an input. Yes, this was already possible in CSS but you could only target the second element, not the first.

label + input { // css goes here }

The code above would style the input where as the previous bit of CSS now targets the label element. This means you have the flexibility to apply your CSS by targeting the container (parent) OR the elements themselves.

Take this example for a form field that has a label and an input that has the required attribute.

... <li class="form-field"> <label for="password">Password</label> <input type="password" id="password" name="password" required /> </li> ...

If I want to highlight the label and input to show that it is missing some information, this would have meant reloading the page or using JavaScript to toggle classes on the page. Not anymore, these are two options I now have. The first would be to use the parent selector to check that the field is invalid:

// element .form-field that has an invalid input, style any labels within it .form-field:has(input:invalid) label { color: red; } .form-field input:invalid { outline: 2px solid red; }

This is how you could target the elements themselves:

// label that is followed immediately by an invalid input label:has(+ input:invalid) { color: red; } .form-field input:invalid { outline: 2px solid red; }

Both are acceptable and possible, I really like the flexibility this brings. Currently, it is limited to version 137+ of Safari Technology Preview and it does have a few bugs. I filled one for issues I had with unordered lists and list items. I also had issues while experimenting with 'input[type="text"]' for this post, where everything but the 'input' as part of the selector were ignored. That's what the Technology Preview browser is for though, discovering bugs.

The really can't come soon enough and I'm glad that at least I've been able to experiment and see how this is going to work once it's widely supported.


Tags: css, development, has-css, html, safari


Tweet WhatsApp Keep Upvote Digg Tumblr Pin Blogger LinkedIn Skype LiveJournal Like