083: :has() tips and tricks

## Metadata
- Author: [[Chrome for Developers]]
- Full Title: 083: :has() tips and tricks
- Category: #articles
- Document Note: ---
tags:
- CSS
- HasSelector
- WebDevelopment
- NoJavaScript
Author: Merlin
Source: CSS Podcast
Reference: https://www.youtube.com/watch?v=UmDgK3OpuZc
date created: 2024-09-14 12:30
---
# Title: Tips and Tricks for Using the `has()` Selector in CSS
## Table of Contents:
1. [π Summary](#-summary)
2. [π Main Content](#-main-content)
- [ποΈ Notes](#-notes)
- [π£οΈ Paraphrase](#-paraphrase)
3. [π° Newsletter Blurb](#-newsletter)
4. [β
Action Items](#-action-items)
5. [π§ͺ Hypotheses and Future Research](#-hypotheses-and-future-research)
6. [π§ Learning Styles Assessment](#-learning-styles-assessment)
7. [π Accessibility and DEIB Assessment](#-accessibility-and-deib-assessment)
8. [β
Logical Validity](#-logical-validity)
9. [π SEO Evaluation](#-seo-evaluation)
10. [π― Conclusion](#-conclusion)
## π Summary:
The `has()` selector in CSS is a powerful tool for styling parent elements based on the presence or state of their children. It is often referred to as the "parent selector," but it is much more versatile, allowing for complex queries and conditional styling based on relationships between elements. With the `has()` selector now supported in all major browsers, developers can use it for creating dynamic layouts, enhancing user interaction, and building creative designs without relying on JavaScript.
## π Main Content:
The `has()` selector can target parents, children, or siblings, creating powerful conditional styling rules. It opens up a range of new possibilities, such as styling a parent element based on the hover state of its children, implementing responsive grid layouts based on the number of items, or even building fully functional web apps like games without JavaScript. Its flexible syntax and ability to chain selectors make it one of the most exciting recent additions to the CSS ecosystem.
### ποΈ Notes:
- **Basic Syntax**: `element:has(selector)` applies styles to an element if it contains or is related to a child or sibling that matches the selector inside `has()`.
- Example: `figure:has(figcaption)` styles a `figure` element only if it contains a `figcaption`.
- **Advanced Use Cases**:
- **Hover Within**: `card:has(:hover)` can style a card based on its child elements being hovered.
- **Quantity Queries**: Use `has()` with `nth-child` to style elements based on the number of children (e.g., for a dynamic grid layout).
- **Chaining**: You can chain `has()` to check multiple conditions (e.g., `figure:has(figcaption):has(img)`).
- **Performance Considerations**: Complex selectors can affect performance, especially in large DOMs. Use with caution and always optimize.
### π£οΈ Paraphrase:
1. "The `has()` selector lets you apply styles to parent elements based on the children they contain. It opens up numerous possibilities for dynamic layouts and user interactions without the need for JavaScript."
2. "Using `has()` with combinators allows developers to create flexible and powerful style rules. For example, you can style elements based on whether they have a specific sibling or even target grandparents in the DOM."
## π° Newsletter Blurb:
π **Web Development Highlight: Mastering the `has()` Selector in CSS** π
Exciting news for web developers! The `has()` selector is now fully supported in all major browsers, and itβs more powerful than ever. Think of it as a βparent selectorβ on steroids! Whether youβre building dynamic layouts or creating complex interactions without a single line of JavaScript, `has()` makes it possible. Check out our latest guide with examples of how to use it for hover effects, quantity queries, and even grid layouts. Ready to level up your CSS game? Dive into the full tutorial and learn how `has()` can transform your projects.
## β
Action Items:
1. Use `has()` for dynamic parent-child and sibling relationships in CSS, eliminating unnecessary JavaScript.
2. Implement `has()` in WordPress themes for more interactive, responsive designs.
3. Educate contributors on the benefits of `has()` in improving the performance and maintainability of CSS in open-source projects.
4. Consider advocating for `has()` in developer training materials and future talks, focusing on its versatility and role in simplifying web development.
## π§ͺ Hypotheses and Future Research:
- **Hypothesis**: Implementing `has()` selectors in responsive layouts can reduce code complexity by up to 30%.
- **Future Research**: Investigate performance impacts of complex `has()` chains on large websites. Explore potential for `has()` in combination with new pseudo-elements.
## π§ Learning Styles Assessment:
1. **Visual Learners**:
- **Present**: The examples provided include selectors and code snippets.
- **Improve**: Add more visual diagrams showing how `has()` affects different DOM elements.
2. **Aural Learners**:
- **Improve**: Include audio explanations or a podcast episode discussing advanced `has()` use cases.
3. **Verbal Learners**:
- **Present**: The explanations are clear and detailed, with lots of examples.
- **Improve**: Add more analogies to explain complex selector chains.
4. **Physical Learners**:
- **Improve**: Include interactive exercises where users can apply the `has()` selector in real-time.
5. **Logical Learners**:
- **Present**: Clear, step-by-step logic in code examples.
6. **Social Learners**:
- **Improve**: Link to community discussions or forums about best practices with `has()`.
7. **Solitary Learners**:
- **Present**: Encourage reflection on how `has()` can reduce JavaScript dependency.
8. **Naturalistic Learners**:
- **Improve**: Draw parallels between DOM structures and real-world hierarchical relationships.
## π Accessibility and DEIB Assessment:
- **Screen Reader Compatibility**: Ensure all visual elements, especially those affected by `has()`, have proper alt-text.
- **Keyboard Navigation**: Test that all interactions affected by `has()` (e.g., hover-based styling) are keyboard accessible.
- **Inclusive Language**: The content avoids jargon but could benefit from defining technical terms for beginners.
## β
Logical Validity:
- **Strong Inductive Reasoning**: The article logically explains how `has()` extends CSS capabilities, backed by examples and clear reasoning.
- **No Fallacies**: There are no major logical fallacies; the arguments are coherent and well-supported.
## π SEO Evaluation:
- **Keywords**: "CSS `has()` selector," "parent selector," "web development."
- **Meta Description**: "Learn how to use the `has()` selector in CSS for dynamic layouts and interactions without JavaScript. Full browser support now available!"
- **Content Length**: Meets ideal length for a technical tutorial, at approximately 2,500 words.
## π― Conclusion:
The `has()` selector is a game-changer for CSS, offering new ways to style elements based on their relationships in the DOM. With its broad browser support and flexible syntax, it's time to start incorporating `has()` into modern web development workflows, reducing dependency on JavaScript and simplifying CSS logic.
Short Summary for [083: :has() tips and tricks](https://www.youtube.com/watch?v=UmDgK3OpuZc) by [Merlin](https://merlin.foyer.work/)
Title: Utilizing :has() Selector for Flexible CSS Styling and Selection
[00:06](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=6) The has selector in CSS allows selecting parent elements based on children
[02:11](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=131) Using 'has' selector with CSS
[06:13](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=373) Use :has() for specificity in styling and be cautious with selectors
[08:18](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=498) Selector List in has is not forgiving
[12:16](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=736) Styling list items based on quantity
[14:23](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=863) Utilizing :has() in styling to dynamically adapt grid layout based on item count.
[18:07](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1087) Using the has() technique for slide-out menus and theming
[20:01](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1201) Utilizing 'has()' to filter and apply view transitions
[23:54](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1434) Demonstrating CSS selector 'has()' with adjacent sibling selection and controlled scaling
[25:44](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1544) Selecting elements before and after hover
[29:27](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1767) Use of 'has()' function for styling and interactivity in CSS.
[31:22](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1882) Developers want more control over inert elements
[35:04](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=2104) Encouraging listeners to engage with the CSS podcast
---------------------------------
Detailed Summary for [083: :has() tips and tricks](https://www.youtube.com/watch?v=UmDgK3OpuZc) by [Merlin](https://merlin.foyer.work/)
Title: Utilizing :has() Selector for Flexible CSS Styling and Selection
[00:06](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=6) The has selector in CSS allows selecting parent elements based on children
- has selector enables selecting specific parent elements based on the presence or state of their children, making it a powerful feature in CSS
- With the has selector and combinators, CSS becomes extremely flexible, allowing for styling children or siblings and solving real-world problems
[02:11](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=131) Using 'has' selector with CSS
- The 'has' selector is supported in 91.8% of global browsers.
- Basic usage includes checking if an element has specific child elements to apply styles.
[06:13](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=373) Use :has() for specificity in styling and be cautious with selectors
- Consider the power of an ID when using :has() with selectors, be more specific and break out individual selectors for better control.
- You can chain :has() selectors but cannot nest them. Use chaining for better control over selecting nested elements.
[08:18](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=498) Selector List in has is not forgiving
- The selector Lis in has takes the highest specificity of the item in the selector list, but it negates the whole line if there is an invalid selector.
- Due to the non-forgiving nature, any error or invalid selector inside the selector list renders the entire line invalid. A workaround is using a forgiving selector like ':wear' to make the line valid.
[12:16](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=736) Styling list items based on quantity
- Using 'has' and 'nth-child' to style parent and list items
- Adding semicolon after each item except for the last item
[14:23](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=863) Utilizing :has() in styling to dynamically adapt grid layout based on item count.
- Using :has() to target specific items based on their position in the grid.
- Adapting grid layout dynamically for varying item counts and screen orientations.
[18:07](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1087) Using the has() technique for slide-out menus and theming
- Targeting the body or root with has() to change custom properties based on selected theme color.
- Using has() for filtering blog posts without JavaScript, as demonstrated by dear code on Twitter.
[20:01](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1201) Utilizing 'has()' to filter and apply view transitions
- Automatically filter content based on support
- Apply view transitions for cool animations
[23:54](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1434) Demonstrating CSS selector 'has()' with adjacent sibling selection and controlled scaling
- Using a sine wave curve to control scaling on hover for adjacent elements
- Demonstrating how 'has()' selector allows selecting adjacent siblings on both sides and multiple directions
[25:44](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1544) Selecting elements before and after hover
- Use .doc Li colon has() to select the element before the hovered element
- Set the width and apply transformations to elements before and after the hovered element
[29:27](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1767) Use of 'has()' function for styling and interactivity in CSS.
- Different features like controlling pointer events and styling based on criteria.
- Clever use of 'has()' to enhance user experience with input fields.
[31:22](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=1882) Developers want more control over inert elements
- Allowing the ability to manage circular focus in popovers
- Utilizing user valid and user invalid methods for simpler code
[35:04](https://www.youtube.com/watch?v=UmDgK3OpuZc&t=2104) Encouraging listeners to engage with the CSS podcast
- Encouraging listeners to ask CSS questions using #CS'sPodcast on Twitter
- Encouraging listeners to share the podcast or leave reviews on podcast apps
- Document Tags: [[css]]
- Summary: The text discusses the versatile ":has()" selector in CSS, which allows for advanced styling and targeting of elements based on their content. It showcases various examples of using ":has()" in combination with other selectors to achieve specific styling effects and layouts. Overall, ":has()" offers a powerful tool for web developers to enhance their styling capabilities with CSS.
- URL: https://www.youtube.com/watch?v=UmDgK3OpuZc&list=PLNYkxOF6rcIAx_S2LSfXQLorIeehsPL3q
[Music] [Applause] [Music] hello and welcome back to the CSS podcast today we're talking about one of my favorite recent additions to the platform which is the has selector has is a flexible selector that lets you select a parent element based on the presence of its children or the state of those children yes that means we finally have a parent selector on the web but
it's actually so much more than that because combining has with combinators in CSS makes it an extremely flexible feature and also just using it to style children or siblings and we've already seen folks do some really incredible things using ha so in this episode we wanted to briefly cover how to use this API a couple of potential gotas and then we get into some great examples of how people are taking advantage of the house selector to solve some real world problem albums and also just to hack
around and have fun and make some cool things yeah this is a super fun one you got to talk about hacking around and having fun has is super fun and awesome and it's much more than just selecting parents Jay called it the family selector which I really liked because you can daverse up and down the elements and their states and select whoever you want you can select you know only only dads that have certain types of children or you can select the children of those kind of dads or whatever it is you can do whatever you need and you can find a yeah you can find a grandpa that has a nephew with three children and then
select those three children it's it's just really powerful it can count how many children anyway we'll get into some of this stuff but exciting news about has also because it's recently landed in all the browser engines meaning this API is now Baseline so cue that Baseline Baseline boom boom I love teasing them about that I'm like how'd you call it Baseline and not have a baseline you're just I need to hear some slap at the base can we can we get a little Baseline Vibe here for yeah hey Lucas out a Baseline
uh landing at both webkit and chromium in 2022 and in Firefox December 2023 so that's why we're Baseline now it's not fresh out the off the Out the Oven but it is uh now it's pretty fresh yeah support is good it's in 91.8 one% of global uh browsers uh as of the recording of this episode so it's now time to get into a bit of how you would actually use has all right so we also
did a quick intro to has in episode 61 so check that out if you want to do a review but in this episode we're going to get even deeper into has so let's start with some Basics on how you use it to get everything up to speed so you can use has with the selector list a very basic way to use has is just like figure colon has fig caption where you're checking to see if a figure has a fig caption inside of it and then you would apply styles to the figure or you could do something like card has highlight
image and that way you're checking to see if a card element has a highlight image inside of it so some kind of image with a class highlight image so both of these would Target the parent element in this case just everything together yes I like calling those the subject of the selector I think that's even what they say in the spec but it's just a nice term because people will call it the parent selector because it sounds like you're selecting the figure parent of a fig caption but even more technically than that it that's just the subject of the ctor is the figure it's not super
relevant that it's the parent it's like what are you trying to actually style are you trying to style the Fig caption or the figure and so this next example we have figure colon has fig caption space fig caption so now the subject of the selector is a fig caption only if it's the child of a figure that has a fig caption so like a lonely fig caption that's not inside of a figure would not match it's required that it's a figure with the Fig in anyway you kind of get it so that but the subject of that is the Fig capture itself yes and you could
take that even further so say you have a figure with a fig caption and inside the figure you also have an image element you could say figure colon has fig caption in the has selector space image so now You' be targeting the image that's the subject here within the figure so it doesn't even have to be that last element it could be something that comes earlier in the Dom tree where you're now styling an image if it's figure has a fig caption so before the Fig caption so it grows it grows yeah
the the subject isn't always on the right with has you can you can change it up you're in control now it's so fun um another good example is figure colon has and that opens up a parentheses fig caption and parentheses space plus space p would Target the paragraph immediately after the figure which is kind of cool yeah and that's also useful if you wanted to create some additional spacing if it has a fig caption versus if it didn't have a fig caption um to differentiate from the caption and the rest of the text so you could definitely
use this stuff in real life these are just some basic examples um and another cool thing about has is that you can combine it with selectors like not to negate the has so you could sort of use this for like a Boolean of has so you could do figure colon not and then open prth Theses then colon has and then open parenthesis and then have fig caption inside that so it's figure not has fig caption I think this is actually quite a nice syntax because to me like it reads very English if the figure does not have a caption then you're styling a figure
that does not have a fig caption nice okay your your tweak to the grammar was good there because I'm like not has that's not how I I not has hunger like that's I think that makes sense well you did well though you're like it does not you do not have hunger Adam you need to fix your not has yes uh very cool so yeah obviously very flexible being able to change the subject and being able to negate and to select uh adjacent elements that are conditional it's it's a very conditional
style selector that also gives you that power to change the subject yes very cool also a note on a specificity the has pseudo class takes on the specificity of the most specific selector in its arguments and this works the same way that is and not do but not the same way that wear does so it works more like is a not just a note on specificity if you're dealing with styling and running into things yeah and also just kind of like the hot tip there is watch out if you're packing on a bunch of selectors in side of the
parenthesis uh this is where that particular thing might come to bite you is that if you put an ID in there all of a sudden your entire selector has the power of an ID which is quite strong yeah almost better be more specific in this case and break out your house selectors than to to pack them in yeah be selective early on be specific early on and then use has and that's probably going to be in that performance tip we get to h a little bit uh another thing so while you know just covered NE negation you can also uh well what you can't do is Nest so you
can't have a has inside of a has but you can chain the has so you can't do figure colon has open parentheses you know figure caption colon has code so if there was code inside of a fig caption that was inside of a figure um that's not going to work and ultimately the subject of that one too was the figure but you can Al you know change it around to say figure colon has open parentheses fig caption and parenthesis so now your subject here is a figure that has a caption but you're going to chain has
code so you're still selecting the figure you're getting the same result but you're just not nesting you're chaining instead um I guess you could also do in that case just like figure has code but there's many cases that you want to chain Nest uh has for there's a lot of use cases for that um so also speaking of checking for multiple things uh you can have multiple selectors in the selector list for has so you could check for something like main has H2 comma H3 uh this would be essentially
like styling a main element that has either an H2 or an H3 so you could have either to match this is so much like uh SQL you know like we're very much writing a query language that's looking up an unknown document size and you're writing all these conditions so yeah the or with a has yeah I really like the syntax of this feature it's really cool I kind of want to query a database with this syntax I bet somebody's done it
uh all right our next little feature that we want to talk about is that the selector Lis in has is not forgiving so youa covered earlier that it takes the highest specificity of the item in the selector list but it is also not forgiving so if you put something in that selector list that's maybe one browser specific or not uh it won't work it will negate the whole line so this was a resolution that was reversed in 2022 because of jQuery the here's the quote the forgiving nature of has breaks jQuery when used with a complex has selector end quote okay so what does
that mean well it means if you have an invalid selector in the list the entire line is ignored like I just uh was explaining but let's imagine really quick here that there's a pseudo element called meow colon colon meow uh which is obviously not valid though I'm maybe there's a way to make it valid where's Jonathan NE when you need him he's like I can make me out valid El which I love that create your own EST pars it through something he's like oh yeah stop me uh he's just great for uh r to challenges
okay so let's say you have main colon has open parentheses H2 comma H3 so if a main has an H2 or an H3 and then you say comma colon col meow well then the entire line would be invalid because there is no meow so everything inside the selector list becomes invalidated because uh it's not forgiving an error was made something was UN unattainable inside of the selector list therefore the whole line is toast but what you could do as a workaround is you can say main colon has open up your parentheses and add a selector in there that is
forgiving and we have the we selector is a forgiving selector and it takes a list also so you would say colon wear open up parenthesis H2 comma H3 comma colon colon meow and then end both of your parentheses and now this is valid because it will still find an H2 or H3 it's forgiving inside of the has before has even knew that there was something unforgiving happening inside of there so you you trick it it's kind of cool yeah nice tip um so speaking of tips let's talk about some tips and tricks we
already talked about some of the basics of has and some basic usage and how to use it um like to check the presence of a child with figure has fig caption we also talked about how you can use this for states or mentioned that at least like you could have card has hover where you'd be able to style a card based on if any of its children were hovered that one's actually really useful yeah hover within basically yeah essentially hover within this technique can also be a standin for Focus within because you could do like nav has Focus where that would be similar to nav Focus within so
uh actually using this for states is super super useful I've definitely done that a few times yep I feel like we covered that in the episode 61 too we were like every pseudo state that there is is now super power to use with has uh which is cool uh and so as we're talking about has you can use it for advanced selection too like as an image element within a figure or the paragraph that follows it and finally we've already mentioned that you can combine it with other selectors like not and where um but let's get into some really interesting and complex examples of
using has like games and Etc what what what do we what do you got where you starting well the first one the first very uh useful use of has for me is quantity queries so this is where you would determine a layout or styling of a parent or the childrenin the parent based on the number of children that it has so this has definitely come up to a few times in my life um one example I like to give is in my previous role I was designing a publishing site where at
the end of this page you could sometimes have an article that had a lot of photographers hairdressers models like credits to give people who are contributing as a part of it um and I had to build this in JavaScript where if it had four or fewer you know credits and I wanted the layout to sort of be block layout where it was one on top of the other to take up a nice amount of space but if it was a bunch like say five or more I wanted this to take up less space because it just like looks like a long list so have those appear in
line so what you can do is use has and use it with nth child to then apply The Styling you can do something like in this case it's a list so UL has nth child n+ 5 this would then style the parent if it had you know five or more items next to each other within it um so then you could build on that where in this case I have UL has n child n plus 5 space Li now I'm styling the list items not the parent so now if it was five or
more items I would display inline um and also I combined this with not and I did like a little trick to add a semicolon after each item except for the last item in that list so now not only am I displaying them inline but I have a line of code that is UL has nth child n plus 5 so five more items Li so space Li not colon last child colon colon after so I'm applying The Styling to every list
item except for the item that is the last child and as a after you know pseudo element it has the content semicolon that is creating that space so I I thought this was like a fun little clever thing that was really hard to do without has and now it's just couple lines of code like some clever styling mixing has and not and once you know the trick of how to use these features really really helpful very cool example I've had to do similar tricks like that in my UI days as well whether it's um adding comos if
you're adding semicolons very cool trick um I've got one here that's a grid styling based on the number of items so another one that's quantity queries and the way that I wrote it so I said like I called this one the always great grid because I'm counting the amount of children and I'm adapting the grid layout based on how many children there are we've all had this problem where it's like uh five items well that means there's a cliffhanger somewhere or dingleberry or whatever you want to call it and you can style that now by quering
how many items are there so in here a good example of this is in the case of five normally someone might take that fifth item and stretch it to the full width I actually take the first item and I Do by that by saying uh the always great grid selectors that's a class that's just the the container for uh this layout and it says colon has do I have a direct child that is the last child that is the nth child five so I look to see is the last one the fifth one and that would mean that I have have a list of five items and then I end my
parentheses for has because I want my subject to be the first child so I do direct descendant selector colon first child and I say hey you span two columns that's it so now it is the promoted item at the top of the list and then I have four nicely placed grid items below it and then this particular demo I kept going with this where I added a button where you could add more items and you could remove items and you would see the grid adapt to two items three items four items five items uh and then I also used view transition
so it was animated and the last little kicker I did was it's in portrait or landscape you get different layouts so we just talked about the first uh child spanning two columns but if I'm in a landscape layout I want the first item to span two rows uh that way it gets a promoted look in the landscape layout so that's why I called it the always great grid because it counts children it knows if it's in a portrait or landscape layout and it adapts and presents itself perfectly in all cases thank you Haz I love this example cuz it's so practical too just the number of times that I have
done a parent class to apply Styles ahead of time to prepare some kind of gallery design layout even on my blog I need to update it because I have it in a while um where I have interstitial inside the blog like different little galleries of images I could just do this with ha I don't have to apply like a two byy or three byy class or four byy based on the number of children I can just have gallery and then use has do a
quantity query and apply The Styling based on the number of children dynamically like that's the way so when I refactor my blog and just maybe I'll do that tonight if I have time nice I think I got the uh the trick too for the selecting inside of has where you say the last child is nth child five I think I got that one from Michelle Barker um as a a great strategy for counting yeah shout out to Michelle always at the edge so good yeah this is super super useful I love that qu queries are so much
easier to create now with has yeah rad okay so you can also use has on the body which has lots of different effects and cool things you can do with one caveat that the more the complex selector that you put in here can slow down your application and if you have a very large page with a lot of Dom elements this one can uh could cause some performance issues because it does have to go up and down the tree you're asking for a lot of work so earlier we were saying you know be specific early on that'll help these things out so like
here's an example let's say you want to remove uh the ability for the page to scroll when a dialogue is open and that's pretty critical because no one likes being able to like scroll the background while they're trying to scroll the dialogue and you can do that one very Simply Now with has you say body colon has open parentheses dialogue Open Bracket with the open attribute so is a dialogue in the open State inside of the body if so style the body because again the the subject here is still the body not the dialogue and we can set the overscroll to Hidden another one is you
can style the body if a menu is open so this could uh like if a popover is open you could slide in a side menu I think you have a very Wicked tweet that did really well that used this technique yeah for the slide out menu yeah using Hal and then another one is theming so of course if you got a a switch on your page that's holding some State about the selected theme color that someone wants you can Target body say colon has what is the state of this theme and then you can change all your custom properties to something else so there's a lot of really cool Powers with using has on the body or has on root whatever is uh that
you need to put it yeah that that could be super useful I liked your performance caveat because um I remember twin was doing this on the route and they had like some really really specific selector for some color on some button and a huge Dom Tree on their homepage and it ended up having some performance slowdowns but really just test because it doesn't necessarily have to there's a lot of factors there um but very useful technique I've seen a lot of examples of this where you're kind of going up the tree you know you mentioned the
grandparent selector this is this could be like a great great great great grandparent selector so y so yeah use with caution um another funky technique that I first saw uh is from a dear code it's a dear code on Twitter his website is AD dear A.D and it is filtering with has using tags so I actually use this on my personal blog now because it was just such an easy way to do filtering for blog posts without any JavaScript just
using has so the way that you set this up is I'm essentially using checkboxes or like check marks for my post so I have this whole filter Bar says showing posts about and then everything so yes that's htl JavaScript design performance a personal post when you uncheck these then it removes any posts about that topic so if I click on them because these are essentially labels for a checkbox it'll remove those posts get more and more filtered as you go um and
it does this automatically and you can also apply view transitions with this so it does like a cool animation so you can like build on this but ultimately it's pretty straightforward um the way that you set this up is first I Teck for support because that's important this is like a pretty critical feature where I don't want all of my post to be display none only if the support for has is there do I set all of my posts to display none okay so we don't have any weird browser
support issues so I have at support selector has a just checking for at supports inside of that everything that's a DOT post so a post card display none and then I have this filter bar where I'm checking if the filter bar has CSS tag checked so if the state of that CSS tag which is you know an ID on um a check mark checkbox then look for the adjacent sibling so using that sort of curly selector uh which is in posts if
the post inside of posts has data tag equals and the data tag which is CSS htl JavaScript whatever it is that aligns to uh the name or the thing that I am showing then display block that item so this sounds like a lot of things going to do a quick review all my posts are hidden then I check if the filter bar has a tag that is checked look for
inside of the adjacent uh sibling combinator inside the posts if a post inside post has a data tag that matches the filter bar then display block so you get all this functionality with no JavaScript just using has and it's progressively enhanced here where I'm just checking for support if not then you don't have the filter bar and you also don't display none the posts so that users could still see the post um hopefully
that helped to explain how this all worked but I thought it was really cool use of has so I wanted to implement it on my page it is a cool use it has and it just gave me a demo idea that I've never seen anybody do it's combining your uh technique here with a recent blog post I had about using starting style and transition behavior on anything and so the whole condition though of that particular uh blog post was that you're animating to and from display none which you're doing right here so if you say starting style is
opacity zero um then when they get presented they're going to animate in and they're going to fade in and then you can say transition Behavior allow discreet on the display none so if they check a checkbox anything that gets hidden is going to fade out and then get displayed unapplied you can literally animate the entry and exit of these elements from the stage all with CSS using has and some check boxes ham that's a great idea I need to add starting Style and those entry and exit effects to this this was definitely out
before those entry and exit effects were landed definitely this stuff is fresh yeah I love it I love it I'm gonna do that Progressive enhancement animation for the win yeah always make sure to use prefers reduced motion everybody and at supports for the has selector if it's a critical user interaction totally nice well very cool demo it was obviously so cool and inspiring that uh it's going to add I'll add this demo to my list of demos that I need to make I have't ever growing uh inspirational list of things to build
all right so we got another example here this one is the apple style dock where the icons scale up based on so if you hover in the middle of the dock the adjacent um icons are scaled up in proportion to the so if you're hovered on the middle one the two next to it are slightly smaller the two next to that are slightly smaller Etc there's a really rad talk from sauna at CSS Day last year you have to watch this I mean the whole talk was absolutely incredible anyway um talking about like pendulums and different mathematics I sine waves so what they did is they they built this
with a sine wave so that when you hovered on the middle one it wasn't just like you know 0.25 scale smaller on the ones adjacent uh he made it a curve and then you could also control the curve so you think about in the doc demo like on Mac OS you can set it to large right so you hover on the middle one and it's very large and then you get this nice curved scale from the adjacent elements that are there he did it all with math uh built in the curve and um what we have now though is bras has made a demo and I think I've made one somewhat
similar as well because the has selector Norm okay so normally in CSS you can only select the elements after one so you can say siblings after me there is no previous sibling selector but the has selector allows you to select adjacent siblings on both sides of yourself and any number of directions from there one to two uh away from you in both directions up the tree and down the tree so bras has a demo that does this they're like oh I I don't I don't have a cool sine wave curve like sauna did but
I do have a quite simplified version that uses has and uh allow me to CSS mouth podcast some code for you and we'll see how well this goes okay so the LI that you're hovering is going to be dot doc so that's the selector for the context of the doc Li colon hover so the one that you're hovering over has a width of three and then you have do doc space Li colon hover and the image inside of there so space image translate zero space 15% so he's using the new uh
shorthand for um transforms so the individual transforms is what they're called as opposed to the transform property which takes a list so anyway he's translating X and Y there with some percentages then the element before and after the hovered Li so here's the kind of crucial part we wanted to talk about we have the one that's after which is very simple which is do doc space Li colon hover plus Li so that's the sibling after me but how do you select the one for you well you say dot doc
space Li colon has open parenthesis so we're no longer in Li hover we're in Li has plus Li colon hover inside of it so you're looking at the element that the one right after it is being hovered therefore this is the one just in front of the hovered element and you can set the width of those two items to point or 2.5m so the one before you and the one after you are 2.5m the one that you're hovering on is 3M and you can also just like how we changed the translate you
can change the translates of those items uh just like they did before so super duper cool um I also did something very similar in a Mini web machine where I used the Looper which is like a radio group essentially and I used the checked pseudo selector to promote the selected one so it's not a hover example this is a checked example so I'm looking at the checked element and I make sure that one's promoted looks nice and big but for some cool visual Intrigue I select the one just before it and just after it and scale them uh slightly about half of what that other one was and then I also animated grid template columns so I have
like grid template columns being animated using the has selector looking at the ones before and after and a radio group of checked element and it creates this really cool I made a plant picker so you could pick a moneria pick Athos whatever um and it as you use the keyboard the one that's selected gets this really cool promoted view anyway has you know it's cool really cool I love that example I think that's a great example of the power of has too where previously as you mentioned you could only select after the you know subject now you can select
before it and that's something we've never had before uh it was super cool to kind of see that live at CSS day it's super cool to like see this also simplified version of it that's feels like really approachable um using hats so like lots of cool stuff um there's also a lot of cool games and things that you could do with CSS so uh I tweeted out if anyone seen like a cool use case of has recently and Scott gel replied and shared a post that he had recently written about how he recreated wle with
just HTML CSS leveraging has the Crux of this is essentially it's a table I mean if you look at the source you know the word but uh within the table you have all of these um you have table rows like inside of this you have like these table cells where you have an input and that input has a specific pattern I also think that this is a very underused HTML feature pattern P attribute of inputs yeah age so uh the
pattern there is you know the letters that you can use and then uh essentially you submit these when this would be either valid or invalid once you enter the text and he's using has in a couple of ways so the first way is to sort of uh invalidate the area only when you're not focused on it so this is like if you have your TR like your cell there not has input placeholder shown and the input is focused then if the input type
equals text is invalid so that input is invalid it doesn't match the pattern the background color is light gray so it Grays it out it doesn't work for that uh element oh also I will say there's no yellow Scott I was very confused because I was like when I played this game first uh usually yellow and rle means that the word letter exists but it's not the right spot this only has is it the right letter in the right spot or is it not mentions that in his blog post he's like there's one feature cliff hang and I
maybe I could figure it out one day but he's like I stop here but it was a creative example so I'm going to keep talking about anyway um so you get either light gray or if it's valid you get the light green background um there's also a neat feature where he's using has to disallow any pointer events until the previous row has been populated oh nice that was clever so you can't just like type further on so you have your table row TR has input placeholder shown and then uh adjacent
to bling selector TR space input comma TR not has input placeholders shown comma input Focus so also after you're done focusing the input then have pointer events none so this disallows it until you've finished with the input um and then he also uses has to like announce the win so there's a couple of different use uses of has here um validate only the non-focused populated row uh I'm not going to get into all of the
uses of has because there's a few of them but it's really fun to see this combination of pattern you know input and has to recreate this version of wle in H2 CSS and we'll we'll link a the post also up in the show notes and you could check it out there's a demo in there um it's very fun it's funky I got two two comments there uh setting pointer EV events from CSS means means that a keyboard user could still get in there which means that this is a good
argument for being able to inert things from CSS we can Mouse inert things from CSS but we can't actually inert things from keyboards or screen readers so uh we only have a partial implementation of something that clearly people want to do they want to be able to visually inert something or just do it from CSS based on some other kind of logic so that's kind of a cool thing I think we need to have more control over inert in general like the ability to inert the page with something like a popover if you wanted where you could control uh you know Focus that like if you wanted to manage
circular Focus inside of a popover like these are options I think developers want to have and I don't know if it's necessarily because they like the ergonomics to pop over which we're going to get with invokers or if it's the ability to kind of cycle within any kind of experience or trap Focus um that's an aside yeah that was an aside I have another side too which is uh the the placeholder shown example with focus and placeholder shown those are methods to work around user invalid and user valid
which we now have so yeah he could totally use user invalid and user valid here yeah which would uh make the code a little bit simpler achieve the same effect um Scott gel very cool though gotta say all right do you have any cool games you want to talk about the usaz yeah I got a Jay made so Jay did for like about a year all sorts of really rad um they looked three-dimensional um but it was like mocked 3D which is sort of like boxes that he was positioning 3D and kind of I mean it was 3D it was it was a 3D rendered CSS scene with
perspective and he would make these so anyway he did Connect Four and built the whole thing with has and it's the code is out of control you can tell that he built it up just Brick by Brick you know with a with a plan that he had and then eventually got into the Mayhem but the Mayhem all works so you complete the game it takes turns between two players you drop your pieces into the top of a 3D looking Connect 4 thing um and it was all just a has experiment that I believe this one tripped him up for a couple days to too but he eventually got it and uh I I I this is what I would have done
if I was him but once it worked I would have ran around the room dancing you know like and then I'd sit back down again be like okay let's get serious and it looks awesome like it is a beautiful 3D Tic Tac Toe board and you can like hover the pieces at the top and drop them in so really really complex CSS game made out of no JavaScript yep very cool I love that this kind of reminds me um years ago I was back in my day long time ago I um I
was interviewing for a company and the interview question was to create a tic-tac-toe game right like you know just build it um so I ended up building it with CSS only the tic tac toe game like it took turns with animations and uh this was a while ago and then I used ultimately like just checking for every position possible value with checkboxes um for
the Tic Tac Toe positions to identify if you won or not so I would check for X's nose that way and it was super super long you know selectors to be able to do that has really really simplifies this like using has could really shorten that code I kind of want to rebuild the Tic Tac Toe now I'm sure somebody has at this point uh using has I'm sure if I Google Tic Tac Toe with has I'll find it right away um but that was really fun like a fun little little brain uh Vibe little experiment to see
if it was possible and now I'm getting it should do it again with has CU I I feel like you really can ah feel the itch that's what this show is good for we make you itchy itchy to write CSS now I'm Googling has tic-tac-toe no JS has tic-tac-toe uh I'm not finding it right away but that doesn't mean that doesn't exist because it must it must it must all right are we are we at the end
yeah we're feeling the end here yeah I mean I we went from like being Su you were so inspired that the show kind of ended as you drifted away I hope you as a listener have done the same thing that you didn't make it this far because you were like I got to go use ass somewhere I know right I'm still looking for it I'm sure it exists oh no well don't worry I'll just recap everything I'll I'll do the ending credits here while you continue your search thank you all for joining us on
the CSS podcast if you have any CSS questions we'd love to answer on the show just tweet us with the hasht cs's podcast I'm unit at un and I'm also at AR link RG y l i in K question can help a lot of people and if you like the show give us a review on whatever podcast app you're using or share this with a friend those reviews they help other people discover a show help us have time to deliver better content for you hey Adam it's your turn to say thank you looking forward to your questions and youa it's time for you to say we'll see you next time bye everyone thank you Adam I'll just have you do that for the rest of the
episodes this season no see y'all [Music], 083: :has() tips and tricks, Chrome for Developers, 01j1xcktp3nw50xr40ke1vr44f.