brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: :focus-within highlights the whole group around a focused input

Web-Development
~/tips/tip-css-focus-within-form-group

.field:focus-within {

Styles a container while any element inside it has keyboard focus.

Styling the input you are typing in is easy. Styling the label and the box around it used to need JavaScript, and :focus-within removes that need.

MDN describes :focus-within as matching an element if the element itself or any of its descendants has focus. Put it on the wrapper:

.field:focus-within {
  border-color: royalblue;
  background: #f4f7ff;
}

With this markup, the whole .field box lights up while the input has focus, label included:

<div class="field">
  <label for="host">Host</label>
  <input id="host" type="text">
</div>

MDN lists it as widely available, and it has worked across major browsers since January 2020, so no fallback is needed. A common use on the MDN page is highlighting a whole form or a group of fields when one input inside it receives focus. A dropdown menu that stays open while something inside it has focus is another good fit, since the focus can sit on a link several levels down.

The caveat is accessibility. The pseudo-class is a visual extra on the wrapper. Do not remove the input’s own focus outline because the group has a style now, because keyboard users still need to see exactly which element has focus. Check that the new colours contrast enough with the text as well. If you only want a ring when the keyboard is used, :focus-visible on the input is the related selector to look at.

Further reading: MDN: :focus-within

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link