when child element has only :focus-visible, how to get parent element :focus-within?
Asked Answered
C

1

6

When a child element has only focus-visible, how to get parent parent element focus-within?

I want the parent get outline when focus child by keyboard. But this code is always has focus(outline) when I click to label or checkbox.

How can I do this? I'm trying

.parent:focus-within:not(:focus){ ~~ }

but it failed.

This is my code:

.parent:focus-within {
    outline: red auto 1px;
}
.child:focus {
    outline-color: red;
}
.child:focus:not(:focus-visible) {
    outline: 0;
}
<pre>
<label class="parent">
  <input type="checkbox" class="child">
</label>
</pre>
Comorin answered 20/3, 2022 at 12:8 Comment(0)
C
6

This is behavior is not supported by :focus-within, but it is possible using :has()

.parent:has(:focus-visible) {
  outline: red auto 1px;
}

.child:focus {
  outline-color: red;
}

.child:focus:not(:focus-visible) {
  outline: 0;
}
<pre>
<label class="parent">
  <input type="checkbox" class="child">
</label>
</pre>

:has() browser support

Castora answered 21/9, 2022 at 21:47 Comment(1)
An excellent solution. To be clear, the first rule is all that is required to mimic a sort of :focus-visible-within behavior. This answer should be accepted.Maidel

© 2022 - 2024 — McMap. All rights reserved.