Skip to content

Repository files navigation

Focus Within

NPM VersionBuild StatusSupport Chat

Focus Within lets you style elements when they are focused or contain a focused element, following the Selectors Level 4 specification.

.fieldlabel {
/* style a label */
}
.field:focus-withinlabel {
/* style a label when its field also contains a focused element */
}

Usage

From the command line, transform CSS files that use :focus-within selectors:

npx focus-within SOURCE.css TRANSFORMED.css

Next, use your transformed CSS with this script:

<linkrel="stylesheet" href="TRANSFORMED.css"><scriptsrc="https://unpkg.com/focus-within/browser"></script><script>focusWithin(document)</script>

That’s it. The script is 379 bytes and works in all browsers, including Internet Explorer 9.

How it works

The PostCSS plugin duplicates rules containing :focus-within, replacing them with an alternative [focus-within] selector.

.field:focus-withinlabel {
font-weight: bold;
}
/* becomes */
.field[focus-within] label {
font-weight: bold;
}
.field:focus-withinlabel {
font-weight: bold;
}

Next, the JavaScript library adds a focus-within attribute to elements otherwise matching :focus-within natively.

<htmlfocus-within><bodyfocus-within><formfocus-within><divclass="field" focus-within><labelfor="a">Field</label><inputid="a" value="This element is focused" focus-within></div><divclass="field"><labelfor="b">Field</label><inputid="b" value="This element is not focused"></div></form><p>Some sibling text element.</p></body></html>

GOTCHA!

One cannot simply add the [focus-within] selector to an existing rule:

.field:focus-withinlabel, .field[focus-within] label {}

Browsers that don't support :focus-within will throw the entire rule away! This is why you should follow the Usage instructions.

About

Style elements when they are focused or contain a focused element

Resources

Contributing

Stars

71 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages