Be wary of the CSS comma selector and pseudo-classes
You’re probably aware of the comma separator in CSS selectors. They’re a handy way to have a set of CSS attributes applied via multiple selectors in one go.
You’re probably also aware of pseudo-classes (sometimes referred to as pseudo-selectors). They give your selector some smarts. For example “input:focus” applies only when the input element has focus.
I recently ran into a problem when I used both at the same time. The site I work on has a menu that is meant to only be scrollable when the mouse is over it (to hide the scrollbar). We used the “:hover” pseudo-class to accomplish this behaviour.
To improve the experience for users that aren’t using a mouse, I wanted to make it scrollable if the user had focus within the div instead. This would allow users with accessibility issues to scroll the div too, since they sometimes can’t use a mouse.
Luckily there’s a pseudo-class for that… :focus-within.
This worked for almost all our users but it broke all scrolling of the menu in Edge (and IE), even on hover. But why?
The answer is that Edge and IE don’t have support for the “:focus-within” pseudo-class and if the browser doesn’t recognize a pseudo-class the whole selector is ignored, even if the browser can understand the selector on the other side of the comma!
This was surprising to me because browsers are typically very good at skipping over CSS it doesn’t like. You can add CSS attributes that only the latest browsers understand and old browsers will safely ignore them. You can also have a selector the browser doesn’t understand, and it’ll be safely ignored.
Here’s the fix:
So be careful out there, if a browser doesn’t like part of a selector, the whole thing is thrown out, even if it looks safe.
BTW, I checked and other browsers also behave this way if they don’t recognize a pseudo-class. Edge/IE users were only affected because it didn’t support “:focus-within”.