Some use cases for the :has() selector in CSS

Week 235 was posted by Charanjit Chana on 2022-04-25.

I'm most definitely a fan of the new :has() selector in CSS. It's only available in Safari for Mac and iOS at the moment, but it's going to be a game changer.

I wanted to highlight some of the use cases I've come across in the past few weeks on Twitter, both as a record for the future and as a reference for myself when I might find myself stuck looking for a pure CSS solution.

Conditional styling

:has() + container queries = the component-based logical styling we've always dreamed of 😍 In this demo: 🖼 If the card has an image: make the font smaller & at < 400px wide, stack it ✨ If no image: bigger font, no stacking https://t.co/UJuXCXUrvV ⚠️ Need flags on in Canary

View on twitter

Style forms and form sections depending on the state of their children

```#css label:has(> :disabled) { cursor: not-allowed; } ``` a future where labels wrapping inputs can easily match the style of a child! caniuse? nope. but it's getting hacked on https://t.co/jE3lmMgK64 :has() spec https://t.co/adwsr1Z5Cw more @css https://t.co/bOyWqc9jJA

View on twitter

Dynamic themes

💡The CSS :has selector is magical! You can theme a website via a select menu and change the CSS variables. No JS is needed! html:has(option[value="purple"]:checked) { --color-1: purple; --color-2: orchid; } Article: https://t.co/s3A291Grp4 Demo: https://t.co/8kyK4LYMCV

View on twitter

Toggle option visibility

One of my favorite use cases of CSS :has is toggling an input based on the checked value from a <select> menu. ```css form:has(option[value="other"]:checked) .other-field { display: block; } ``` Details: https://t.co/49iqFpR5l4

View on twitter

Detect if there are errors on the page

💡 CSS :has allows us to check if the main section contains an error and adjust the header accordingly. Neat! 🤩 .main:has(.alert--error) .header { border-top: 2px solid red; background-color: #fff4f4; } Article: https://t.co/tLTNSLxZo4 Demo: https://t.co/tt7uXynXYr

View on twitter

With all of this at our disposal, when you think about how the web used to be built we no longer need to make a request to a server to figure out what the correct markup should be and maybe hydrate the page with JavaScript once things change. With the way the web works now, the whole presentation layer can live in CSS. That's exactly where it's meant to be.


Tags: css, development, has-css


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