惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
PCI Perspectives
PCI Perspectives
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The GitHub Blog
The GitHub Blog
S
Secure Thoughts
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
WordPress大学
WordPress大学
SecWiki News
SecWiki News
B
Blog
小众软件
小众软件
Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
L
LINUX DO - 热门话题
Recent Commits to openclaw:main
Recent Commits to openclaw:main
酷 壳 – CoolShell
酷 壳 – CoolShell
IT之家
IT之家
The Cloudflare Blog
Google DeepMind News
Google DeepMind News
Know Your Adversary
Know Your Adversary
Y
Y Combinator Blog
F
Fortinet All Blogs
W
WeLiveSecurity
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
Last Week in AI
Last Week in AI
The Last Watchdog
The Last Watchdog
S
Schneier on Security
爱范儿
爱范儿
V
V2EX - 技术
L
LINUX DO - 最新话题
月光博客
月光博客
博客园 - 【当耐特】
Latest news
Latest news
阮一峰的网络日志
阮一峰的网络日志
博客园 - 司徒正美
U
Unit 42
Schneier on Security
Schneier on Security
E
Exploit-DB.com RSS Feed
J
Java Code Geeks
Cyberwarzone
Cyberwarzone
T
The Blog of Author Tim Ferriss
TaoSecurity Blog
TaoSecurity Blog
博客园 - 叶小钗
T
Troy Hunt's Blog
大猫的无限游戏
大猫的无限游戏
AI
AI
Security Latest
Security Latest

Matthias Ott

Hello Again, World This, Still Not for Everyone The Shape of Friction WeissKlang L1 – Punching Above Its Weight Continvoucly Morged Value Webspace Invaders To Affinity and Beyond The Mystery of Storytelling Amateurs! Echoes of Connection Linear() Is Not (That) Linear View Transitions: The Smooth Parts Adding AVIF and WebP Support to My Craft CMS Site Challenge Acoustic Room Treatment and Building Sound Panels, Part 1: Planning Play On Overshoot The HTML Output Element Listening Closely Compressed Fluid Typography The Lifeblood of the Web What Could Go Wrong? That’s My Rank Making Space CSS :is() :where() the Magic Happens Visual Regression Testing for External URLs With Playwright Jane Goodall’s Famous Last Words European Tech Alternatives 🇪🇺 Independent Type Foundry Advent Calendar – Day 24: NaN Independent Type Foundry Advent Calendar – Day 23: Typotheque Independent Type Foundry Advent Calendar – Day 22: 205TF Independent Type Foundry Advent Calendar – Day 21: HvD Fonts Independent Type Foundry Advent Calendar – Day 20: Frere-Jones Type Independent Type Foundry Advent Calendar – Day 19: Fontwerk Independent Type Foundry Advent Calendar – Day 18: Vectro Independent Type Foundry Advent Calendar – Day 17: Studio René Bieder Independent Type Foundry Advent Calendar – Day 16: R-Typography Independent Type Foundry Advent Calendar – Day 15: David Jonathan Ross Independent Type Foundry Advent Calendar – Day 14: Interval Type Independent Type Foundry Advent Calendar – Day 13: Newglyph Independent Type Foundry Advent Calendar – Day 12: Swiss Typefaces Independent Type Foundry Advent Calendar – Day 11: Sharp Type Independent Type Foundry Advent Calendar – Day 10: Colophon Foundry Independent Type Foundry Advent Calendar – Day 9: Commercial Type Independent Type Foundry Advent Calendar – Day 8: Letters from Sweden Independent Type Foundry Advent Calendar – Day 7: Lineto Independent Type Foundry Advent Calendar – Day 6: Ohno Type Company Independent Type Foundry Advent Calendar – Day 5: Milieu Grotesque Independent Type Foundry Advent Calendar – Day 4: TypeMates Independent Type Foundry Advent Calendar – Day 3: Klim Type Foundry Independent Type Foundry Advent Calendar – Day 2: Dinamo Independent Type Foundry Advent Calendar – Day 1: Grilli Type The Independent Type Foundry Advent Calendar 2022 A Conversation With ChatGPT ChatGPT, please explain websites in the words of William Shakespeare Transient Frameworks Leaving Twitter Behind Converting Your Twitter Archive to Markdown The Wrong Question It Wasn’t Written Syndicating Posts from Your Personal Website to Twitter and Mastodon Suspension None of Your Business Doing Our Part Patch That Package Brain Dump Generating Accessibility Test Results for a Whole Website With Evaluatory The CSS Cascade, a Deep Dive Updates About Updates How to Delete Your Commit History in Git Unblocking Your Writing Blocks, Part 2: I’m Not an Expert nor a “Thought Leader” Connections No Wrong Notes Better Options Design Debt Finite and Infinite Games Don’t Assume, Validate. Necessity Is the Ultimate Teacher One Egg Go Deep There Is No Secret Code Balancing Risk Blue Eyes, Brown Eyes The Shortcut Boomerang My RSS Feed Collection of Personal Websites Frequency The Illusion of Control The Decisions Journey Write It Down Nownownow Into the Personal-Website-Verse Considering the Opposite What is it for? Unlimited Bowling. Never done. We Are Team Internet. We Need to Save #NetNeutrality. Progressive Search Data loss (also) by JavaScript Books I Will Definitely Maybe Read in 2017 Starting to Write Notes
CSS :has( ) A Parent Selector Now
Matthias Ott · 2022-04-11 · via Matthias Ott

I don’t remember the exact moment anymore. But I remember that it was with a mix of disbelief and disappointment that I realized one day that there was no way to select the parent of an element in CSS.

Wait, what? This can’t be. Why?

Obviously, I wasn’t alone. Everyone who has ever learned CSS has probably found themselves in the same situation and asked themselves the same question: Why is it that we don’t have a parent selector in CSS? As Jonathan Snook described in an elaborate post back in 2010, it was not only because of performance concerns but also because of the way browsers render a document and apply the computed styles to elements: as a stream, one element after the other as they come in. When an element is rendered to the viewport, its parent is already there, including all its beautiful styling. Repainting the parent – and, consequently, all other parents – after the fact would then require another evaluation of all parent selectors. This, Remy Sharp agreed back then, would again be so expensive on the render engine that it wouldn't make sense to implement a parent selector.

So, we all accepted the inevitable and did our best to work around it. We added helper classes to our templates via back-end logic or with JavaScript in the frontend. And it somewhat worked. But in almost every project, there still was this one moment where a parent selector would have been the quickest and most “materially honest” solution.

:has has arrived #

All of this changed last month when Apple released Safari 15.4 which, as the first browser, supports the :has() pseudo-class, which is one of the CSS Level 4 Selectors. “It was long thought such a selector was not possible, but our team figured out a way to highly optimize performance and deliver a flexible solution that does not slow the page,” Jen Simmons and Jon Davis wrote in the release notes.

There it is. A parent selector. But :has is not only useful as a parent selector. It also opens up a lot more interesting opportunities. But first, let’s have a look at how it works.

The :has pseudo-class takes a relative selector list and will then represent an element if at least one other element matches the selectors in the list. Sounds overly complicated when you write it down, so here is a basic example. Let’s say you want to select all button elements which include an svg element, like an icon. You can now write:

button:has(svg) { … }

Try the CodePen demo – and make sure to view it in Safari 15.4. ;)

Or, if you want to style an article differently if it has a headline inside that is followed by a paragraph:

article:has(h2 + p, h3 + p) { … }

You can also combine :has with the :not pseudo-class to select an element if it does not contain certain other elements, in this case, a headline:

section:not(:has(h1, h2, h3, h4, h5, h6)) { … }

It is also possible to use pseudo-classes like :hover, :focus, or :checked. You could style a form element when a checkbox inside has been checked, for example:

form:has(input[type="checkbox"]:checked) { … }

You could then also use the general sibling combinator ~ to change the styling of the form depending on how many of the checkboxes have been selected:

/* Two checkboxes are :checked… */

form:has(input[type="checkbox"]:checked ~ input[type="checkbox"]:checked) { 
  box-shadow: inset 0 0 0 0.5rem blue;
  background-color: rgb(150, 187, 235);
}

/* Three checkboxes are :checked… */

form:has(input[type="checkbox"]:checked ~ input[type="checkbox"]:checked ~ input[type="checkbox"]:checked) { 
  box-shadow: inset 0 0 0 0.5rem rgb(0, 160, 0);
  background-color: rgb(136, 233, 136);
}

Try the CodePen demo.

Although this demo might not be the most practical example, all this is still starting to get interesting, right?

Using :has to adjust a Grid #

CSS Grid generally works from the container in and before :has, there wasn’t really a way to adjust the Grid based on what’s inside. What if we could use :has to adjust the CSS Grid layout of a container based on the number of elements inside of it? Here, so-called quantity queries can be useful. Heydon Pickering has written the ultimate article about them. By combining the :nth-child and :nth-last-child pseudo-classes inside our :has selector list, we can adjust the layout by “counting” the elements inside. Here is how we can target a grid with two elements inside, for example:

.grid:has(:nth-child(2):last-child) {
  grid-template-columns: 1fr 1fr;
}

So, if our Grid container has an element inside that is both the second child as well as the last child of our container, the grid should have two columns. The same also works with three columns:

.grid:has(:nth-child(3):last-child) {
  grid-template-columns: 1fr 1fr 1fr;
}

Finally, we can also create a grid layout that has four columns if the container has four or more elements inside. To achieve this, we select at least one element that is either the fourth or one of all following elements:

.grid:has(:nth-child(n+4)) {
  grid-template-columns: repeat(4, 1fr);
}

Here is a CodePen demo again.

As you can see, there are lots of amazing use cases for :has as a parent selector and it still feels like this is only scratching the surface of what people will come up with. :has lets us style elements based on whether the child of an element is selected, has focus, or whether it is present at all. And we can even target an element based on how many children it has. All this will allow for much more flexible components. Just think of all the variations of content and context that can exist inside a design system and you know how valuable this will be.

But wait, there is more!

:has as a previous sibling selector #

Because :has accepts a relative selector list, you can also select an element if it has another element that follows it. Or, in other words, we can use :has to select the previous sibling of an element:

:has(+ .second) {
  background-color: darkmagenta;
}

Try it on CodePen.

Again, there are so many practical use cases for this! For example, you could style an image differently when there is a caption below it:

figure img:has(+ figcaption) {
  /* Do something with the image */
}

The possibilities of using :has in useful and creative ways to write more flexible and robust CSS seem endless. And as is the case with so many of the new features that are currently being added to CSS, I can't wait to see what other creative uses for :has you all come up with. One recent example is this brilliant demo by Michelle Barker, where she combines animated grid tracks with the :has selector.

Testing for support #

For now, Safari is the only browser with support for :has. In the upcoming version 101 of Chrome, you’ll be able to activate it via the Experimental Web Platform features flag, however. While this is promising, it will certainly take a little while until :has is supported by the majority of browsers. In the meantime, we can once more use progressive enhancement to already use :has in browsers that support it. As Michelle Barker notes, you can test for support for :has with a @supports feature query using the selector() function:

@supports selector(:has(*)) {
  /* Code for browsers with support for :has */
}

Thus, you can target supporting browsers in a future friendly way. Because once :has is supported by another browser, your code will work automatically in this browser as well.

Do you have more ideas about how to use :has? Have you seen more interesting examples and demos? And will you start using it already? Let me know via Webmention, email, or Twitter.

~