Modern CSS Selectors: :has(), :is(), :where(), and :focus-visible by kirupa (https://www.kirupa.com/me/index.htm) | filed under HTML and CSS (https://www.kirupa.com/html5/learn_html_css.htm) TL;DR: A few newer CSS selectors let styles react to what's inside an element. :has() styles a parent based on its children, like a card with a checked checkbox. :is() and :where() group selectors so we don't repeat ourselves, and :focus-visible shows focus rings to keyboard users without bothering mouse users. - .topping:has(input:checked) styles the card itself, while .topping input:checked can only ever style the checkbox inside it. - :is() and :where() match the same elements, but :is() counts as its most specific argument and :where() always adds zero specificity. - :focus-visible matches keyboard focus and skips mouse clicks on buttons, so there's no reason to remove focus outlines anymore. - All of them work in every current browser, and :has(), the newest, has been everywhere since December 2023. For most of CSS's life, selectors could only look in one direction. A selector could find an element and then reach down into its children, but it couldn't ask a question like, "Does this card have a checked checkbox inside it?" If we wanted to style something based on what it contained, we had to reach for JavaScript and toggle a class by hand. That has changed. A handful of newer selectors let us style a parent based on its children, group long selector lists without repeating ourselves, control how much specificity a selector adds, and show focus rings only to the people who need them. To see all of them working together, here is a pizza order form with zero lines of JavaScript in it: Live demo: A pizza order form with six topping cards, an email field, and a Place order button. Checking a topping highlights its card, the button turns on once something is picked, and an invalid email turns the field red (https://www.kirupa.com/html5/examples/modern_selectors_toppings.htm) Try it: 1. Click a few toppings and watch the Place order button wake up 2. Type zorb into the email field and click somewhere else 3. Press Tab to move through the form with your keyboard Every highlight, every enabled button, and every focus ring in that form comes from CSS selectors. By the end of this tutorial, we'll know exactly which selector does each of those things and why. Onwards! How Do We Style a Parent Based on Its Children? Let's start with the topping cards. Each card is a label element with a checkbox, an icon, and some text inside it: When someone checks a topping, we want the whole card to turn red so it's obvious what has been picked. With the selectors we've always had, the closest we can get is something like this: .topping input:checked { outline: 3px solid #e0605a; } This selector finds a .topping element, looks inside it for a checked input, and styles that input. The styles land on the checkbox, and the card itself stays exactly as it was. That's the one-direction problem from earlier. The thing we style is always the last thing in the selector, and the last thing here is the checkbox. What we really want is a way to say, "Style the card, but only when the card has a checked checkbox inside it." That's what the :has() pseudo-class does: .topping:has(input:checked) { border-color: #e0605a; background-color: #fff1ef; } Read it from left to right. We start with .topping, and then :has(input:checked) filters it down to only the topping cards that contain a checked input. The styles apply to the card, because the card is what we started with: [Image: Two copies of a Mushroom topping card with a checked checkbox inside it. On the left, the selector .topping input:checked styles only the checkbox, which gets a red outline. On the right, the selector .topping:has(input:checked) styles the whole card, which turns red. A callout says the card is picked by what's inside it.] (https://www.kirupa.com/html5/images/sel_has_parent.png) Look at the right card. Nothing about the card itself changed. What changed is the checkbox inside it, and :has() let that change bubble up to the card. This is why people often call :has() the parent selector, even though it can do a lot more than pick parents. It Can Look at More Than Children The argument we pass into :has() is a relative selector. By default, it looks for descendants, but we can start it with a combinator to look in other directions. Here are a few that show up all the time: /* An h2 that is immediately followed by a paragraph */ h2:has(+ p) { margin-bottom: 4px; } /* A list item that has a nested list directly inside it */ li:has(> ul) { font-weight: 700; } /* A field whose input has an email someone typed incorrectly */ .field:has(input:user-invalid) .hint { display: block; } That last one is straight out of our order form. The :user-invalid pseudo-class matches an input whose value is invalid, but only after the person has interacted with it, so the form doesn't yell at someone before they've typed anything. Our .field wrapper uses :has() to notice that and reveal its hint text. We can also turn :has() around and have an element look at its whole subtree. The form uses this to keep its button sleepy until at least one topping is checked: form:not(:has(.topping input:checked)) .order button { opacity: 0.45; pointer-events: none; } In plain words, this says: if this form does not have a checked topping anywhere inside it, fade out the order button. The moment one checkbox gets checked, :has() matches, :not() stops matching, and the button wakes up. There's no event listener and no class toggling. The browser re-checks the selector for us whenever the page changes. There are two limits worth knowing. We can't put a :has() inside another :has(), and we can't use pseudo-elements like ::before inside it. Everything else is fair game. How Do :is() and :where() Group Selectors? The next thing our form does is give the order button and the email field the same blue focus ring. The old way to style two different things identically is a selector list, where we separate the selectors with commas: .order button:focus-visible, .field input:focus-visible { outline: 3px solid #0798ff; outline-offset: 3px; } That works, but notice that we typed :focus-visible twice. If we added a third and a fourth element, we'd type it a third and a fourth time. The part that changes is at the front, and the part that stays the same is at the end, so what we want is a way to list just the changing parts once. The :is() pseudo-class takes a list of selectors and matches any element that matches at least one of them. With it, our focus rule becomes: :is(.order button, .field input):focus-visible { outline: 3px solid #0798ff; outline-offset: 3px; } This is the exact rule our order form uses. It reads as "any order button or field input, when it has visible focus." The savings get bigger when the shared part is longer, or when we are combining two lists. Styling every link and code snippet inside our article headings is a good example: /* Without :is(), this would be six selectors */ article :is(h1, h2, h3) :is(a, code) { color: inherit; } There's one more nice detail. In a regular selector list, if any one selector is invalid (say, a pseudo-class some browser doesn't understand), the browser throws away the entire rule. Inside :is(), the list is forgiving. The browser ignores the selector it doesn't understand and keeps the rest. The :where() pseudo-class matches exactly the same way. Anything we can write with :is(), we can write with :where() and match the same elements. So why do both exist? What makes them different is how much they add to a selector's specificity. What Is the Difference Between :is() and :where()? When two rules set the same property on the same element, the browser picks a winner, and one of the tiebreakers it uses is specificity (https://www.kirupa.com/html5/css_selectors_type_class_id.htm). Specificity is a score with three parts: how many IDs a selector has, how many classes, attributes, and pseudo-classes it has, and how many element types it has. A higher score wins. Here is where :is() and :where() go their separate ways. :is() takes on the specificity of the most specific selector inside it. :where() always adds zero, no matter what we put inside it: [Image: Two selectors that match the same links. :is(#menu, .nav) a scores 1 ID, 0 classes, and 1 type, because it counts as its most specific argument, #menu. :where(#menu, .nav) a scores 0 IDs, 0 classes, and 1 type, because #menu adds nothing inside :where().] (https://www.kirupa.com/html5/images/sel_is_where.png) Look at the IDs column. The :is() version scores an ID even when the link it matches lives inside .nav and has nothing to do with #menu. That's because :is() always counts as its heaviest argument. The :where() version scores zero in that column, and the only point it earns comes from the a that sits outside the parentheses. That makes :where() perfect for default styles that we want to be easy to override. If we are writing a reset, or a set of base styles that other people will build on top of, wrapping our selectors in :where() means any single class can beat them: /* Base styles with zero specificity */ :where(.btn) { padding: 8px 16px; border-radius: 8px; } /* Any class beats it, even one written earlier in the file */ .big { padding: 16px 32px; } A good rule of thumb is to reach for :is() when we just want shorter selectors and to reach for :where() when we want our rules to be easy to override. If taming specificity across a whole stylesheet is the goal, cascade layers (https://www.kirupa.com/html5/css_cascade_layers.htm) take this idea even further. How Do We Show Focus Rings Only for Keyboard Users? The focus ring is the outline that shows which element on the page will react to the keyboard. For someone moving through a page with Tab, it's the only way to know where they are. For someone clicking with a mouse, it can look like a stray box that showed up after a click, and that's why so many stylesheets used to contain this line: /* Please don't do this */ button:focus { outline: none; } That line removes the ring for everyone, including the keyboard users who depend on it. What we actually want is a ring when someone is navigating with the keyboard and no ring when they clicked with a mouse. The :focus-visible pseudo-class gives us exactly that. It matches a focused element only when the browser thinks the person needs to see the focus: [Image: Two copies of the Place order button, both focused. On the left, someone clicked it with a mouse, so :focus-visible doesn't match and there's no ring. On the right, someone reached it by pressing Tab, so :focus-visible matches and the button gets a blue focus ring.] (https://www.kirupa.com/html5/images/sel_focus_visible.png) Both buttons have focus, so :focus would match both of them. Only the right one was reached with the keyboard, so only the right one matches :focus-visible. The browser makes that call using a few simple rules. Keyboard focus is always visible. Clicking a button with a mouse or tapping it with a finger is not. Text fields are the exception, and they show focus even after a click, because the next thing we'll do with them is type. Putting it to work looks like this: button:focus-visible { outline: 3px solid #0798ff; outline-offset: 3px; } Our order form combines this with :has(). The checkboxes are tiny, so drawing a ring around them would be hard to see. Instead, the card draws the ring when the checkbox inside it has visible focus: .topping:has(input:focus-visible) { outline: 3px solid #0798ff; outline-offset: 3px; } Go back to the example and click a topping with your mouse. No ring shows up. Now press Tab a few times, and the ring jumps from card to card. If you want to go further and restyle the browser's default ring, our Changing the Default Focus Styles (https://www.kirupa.com/html5/changing_the_default_focus_styles.htm) tutorial walks through it. Which Browsers Support These Selectors? All of them work in the current versions of Chrome, Edge, Firefox, and Safari. :is() and :where() have been everywhere since early 2021, and :focus-visible since March 2022. :has() is the newest of the bunch, and it has worked in every major browser since Firefox added it in December 2023. If our styles still need to look reasonable in an older browser, we can check for :has() support with @supports and only use it when it's there: .topping.is-checked { border-color: #e0605a; } @supports selector(:has(a)) { .topping:has(input:checked) { border-color: #e0605a; } } The first rule is the fallback, and it relies on JavaScript adding an is-checked class. The second rule only runs in browsers that understand :has(). Older browsers skip the @supports block entirely and keep the fallback. Conclusion For a very long time, a lot of what we did in this tutorial needed JavaScript. We'd listen for a checkbox change, add a class to the card, count the checked boxes, and toggle the button, all to keep the page's styles in sync with its state. With :has(), the page's state is something our selectors can ask about directly, and the browser keeps everything in sync for us. The other selectors make our day-to-day CSS nicer. :is() lets us write a shared ending once. :where() does the same while keeping our rules easy to override. :focus-visible finally lets us stop choosing between a page that looks clean and a page that works with a keyboard. The one thing to keep an eye on is how much JavaScript you've written in the past that a single :has() could replace. It's usually more than you'd think! Before you go, here are a few things you can do: 1. Test your knowledge by taking the quiz below. 2. Check out some related content: - Cascade Layers in CSS (https://www.kirupa.com/html5/css_cascade_layers.htm). Decide which group of styles wins before specificity even comes up. - Nesting in CSS (https://www.kirupa.com/html5/css_nesting.htm). Write rules inside rules and keep a component's styles together. - Changing the Default Focus Styles (https://www.kirupa.com/html5/changing_the_default_focus_styles.htm). Restyle the browser's built-in focus ring. 3. Stuck on something, or curious about a detail we skipped? Ask on the forums (https://forum.kirupa.com/), and we'll help you out. [Mastery Quiz] Test your knowledge! Take the Reviewing Modern CSS Selectors Quiz: https://www.kirupa.com/quizzes/modern_css_selectors.htm Practice with 4 multiple-choice questions and an explanation after every answer. [/Mastery Quiz]