Search code examples
htmlcssstyled-components

Outline-offset property jumps to parent component


I have a checkbox input with a label, all wrapped up in a div container. I am using styled-components with React but this is the rough structure of the component:

<CheckboxWrapper>
  <input type="checkbox" />
  <label>Label</label>
</CheckboxWrapper>

What I want to achieve is to customize the :focus state of the component. By default it is set to an outline around the checkbox, but I want to set it around the whole wrapper. This is my css code:

input:focus + label {
  border-radius: 4px;
  outline: 2px solid black;
  outline-offset: 24px;
}

The outline on focus works fine, but the outline-offset property is completely gone when I inspect the component in any browser. And to my complete surprise, I then discovered it is being applied to the parent component. That is, the CheckboxWrapper now has a solitary outline-offset property applied. What the heck?

I found a similar problem posted on this 9 year old post. I tried all the answers listed on that post to no avail (applying display: inline-flex, outline-style: solid...). Besides, the bug happens also in Firefox.


Solution

  • I ended up finding a way more elegant solution:

    .wrapper:focus-within {
      box-shadow: ...
    }