Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:focus-within when focusing first child but not the last

Tags:

css

focus

I have a <section> element that I want to set focus within only when the first child element receive focus but not the second. I tried using the :not pseudo-class but that didn't work out.

Worth noticing that I still need to have focus on the second element, just don't want to have two focused elements (parent + child) as the example below.

Codepen example

Better if a HTML/CSS only hack/solution.

like image 552
Cezar Augusto Avatar asked Feb 11 '19 17:02

Cezar Augusto


People also ask

What does focus within do?

The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus . (This includes descendants in shadow trees.)

What does the focus pseudo-class do?

The :focus CSS pseudo-class represents an element (such as a form input) that has received focus. It is generally triggered when the user clicks or taps on an element or selects it with the keyboard's Tab key.

What is the opposite of focus in CSS?

To wit: the :focus pseudo-class represents an element that is in focus; it does not represent an element that has just received focus, nor does there exist a :blur pseudo-class to represent an element that has just lost focus.

What is the difference between focus and focus visible?

This state is usually indicated using the outline . Adding the :focus pseudo-class to an element will make it show a focus specific styles and disregard browsers heuristics. The :focus-visible , in contrast, applies custom styling only if it would be shown natively.


1 Answers

":focus-within" makes the parent element to have focus if any of its children have focus itself. You can't do this only with css, as you can only select elements that are siblings or children, except for this unusual case that selects the parent (even though you can't select which element has focus inside). You are applying the focus within to the section, not to the children.

like image 121
nara92 Avatar answered Oct 19 '22 03:10

nara92