今日已更新 133 条资讯 | 累计 37382 条内容
关于我们

CSS Just Got a Parent Selector. Your Forms Will Never Look the Same

Artclick 2026年08月13日 14:20 4 次阅读 来源:Dev.to

For as long as I've been writing CSS, there's been one direction it refused to look: up. You could style a child based on its parent all day long, but the second you wanted a parent to react to something happening inside it — a checked checkbox, an invalid field, a filled-in input — you were reaching for JavaScript. Every time. It didn't matter how small the interaction was. :has() breaks that rule on purpose, and it's been safe to use in production for a while now — it's supported across Chrome, Edge, Firefox, Safari, and Opera, no polyfill required. I didn't fully appreciate what that meant until I rebuilt a form I'd been maintaining for two years and deleted most of the JavaScript in it. Not all of it — I'll get to where it still earns its place — but most. The rule CSS used to have /* This has always worked: style a child based on the parent */ .card.featured .title { color : gold ; } /* This has never worked, until :has(): style the parent based on a child */ .card :has ( .badge--sold-out ) { opacity : 0.6 ; } :has() reads as "select this element, if it contains a match for whatever's inside the parentheses." Once that clicks, a huge category of things people were writing classList.toggle() calls for turns into a single selector. Styling a label when its input is focused This used to mean a focus and blur listener on the input, toggling a class on the label. Now: .field :has ( input :focus ) { border-color : var ( --accent-color ); box-shadow : 0 0 0 3px color-mix ( in srgb , var ( --accent-color ) 25% , transparent ); } Wrap the label and input in a .field container, and the whole field lights up the moment the input inside it gets focus — no listener, no class toggle, and it can never drift out of sync with the actual focus state, because it is the actual focus state. Required-field indicators that can't go stale I've fixed this bug more times than I want to admit: a form gets a field added, and someone forgets to also add the little red asterisk that's suppo

本文内容来源于互联网,版权归原作者所有
查看原文