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.
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.)
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.
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.
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.
":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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With