Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between :focus via tab-key and :focus via click in CSS

Tags:

css

Although I am quite certain that the answer to my question will be "Can't be done" I'd like to be sure and ask you guys here.

I have a rather typical scenario in which I want to enable tabbing through my website (i.e. using tab key on keyboard). The item the user has just tabbed upon should be marked visually via CSS. So far, so good. This, obviously, demands the focus-pseudo class:

a {
    color: #000;

    &:hover {
        color: lighten(#000, 10%); // discreet change
    }

    &:focus {
        background-color: green; // extreme change
    }
}

But I want to apply this style solely when the user tabs through the page. When the user hovers or clicks an element the style should be something different.

Example: A user hovers or clicks an anchor. Then the visual aid can be discreet because the user already knows which element he has interacted upon. But when he tabs through the page he can not be so sure and thus the styling should be more drastic.

The problem I am having is: An element gets the focus-styles applied on on both tabbing the page and clicking on it.

Is there a CSS-only way to apply styles solely when an element got focused via tabbing?

Again, I am pretty sure that this is not possible, but just to be sure I have asked the question.

like image 342
hurrtz Avatar asked Feb 05 '23 17:02

hurrtz


2 Answers

There's a new CSS selector :focus-visible that is intended to solve this scenario by targeting only the elements that were focused via keyboard input.

This is only supported natively in Firefox today, however there is a polyfill that makes this possible in all browsers through a .focus-visible class name.

like image 91
heff Avatar answered Feb 07 '23 17:02

heff


The :focus pseudo-class does not discriminate based on how the element entered focus in the first place. So indeed, this is not possible with just CSS. At the very least you'd need to annotate the element on focus via an event handler.

The :hover and :active pseudo-classes won't be of any help here since the former only applies when the mouse pointer is on the element and the latter only applies when the mouse button is down, i.e. neither state persists the way :focus does, since an element remains in focus even after the mouse pointer has left the element, making it indistinguishable from an element that received focus via tabbing.

like image 23
BoltClock Avatar answered Feb 07 '23 18:02

BoltClock