focus-visible-within : Art of mastering focus

focus, focus-visible and focus-within — what are they?

Hello Everyone !!

Focus !!!

Why this is important?

A Website can be operated via mouse and via keyboard. If we are always operating a website by mouse we might not feel the difference.

But when we navigate a website using Keyboard, the difference is clearly visible. and in this case apply correct CSS for focus state can be a game changer.

Wait What? Why Do I ever navigate a website via keyboard?

Well there can be many reasons. Like navigating via keyboard can be easy for some one, and for some person it might be difficult to use mouse.

So How do we navigate a website using keyboard?
Via Tab key, Tab key toggles focus from one element to another. And focus element can be triggered via space or enter key.

When a website is operated using keyboard, we have to show some visible feedback to the user, which indicates the currently selected element.

Generally we do this via focus state via CSS. We simply add border around the element, in case the element got focused.

Different type of focus state.

:focus — for both mouse and keyboard

Cons: Style added when focus is added via mouse. Generally we don’t want to show any UI feedback when focus is added via mouse.

button:focus {
border: 2px solid black;
}

:focus-visible: for keyboard only

Ideal choice add to add styling to focused elements.

Pay attention to border added on elements.

:focus-within: both mouse and keyboard

we use this to add style to parent element, whenever child element got focus.

Cons:
Styling applied even when focus is applied via mouse.

form:focus-within {
background-color: lightpink;
border:2px solid lightcoral
}
Clicking Buttons, adding focus to paren. Pink Color.

So How can we implement something link :focus-visible-within or :focus-within-visible like functionality because we don’t have such property in css.

What we want is, to add styling to parent only when child gets focused via keyboard.

We can achieve this via :has selector.

.parent:has(:focus-visible) {
// styles
}

What we are telling the browser is, to check if .parent class contains
any :focus-visible state. then apply the provided css to .parent.
Parent getting focused, when keyboard is used. On Mouse Click no styling is applied on parent

Caveat of this approach:

If you have form elements, for elements :focus-visible is activated even when we focus using mouse. In such cases, when you select a form element by mouse, then parent element will get focus-visible-within style applied.

Let me know what do you think about this approach.

--

--