Free · Private · In-Browser

CSS Focus Within Preview

Try :focus-within on real controls and copy the CSS.

 

How :focus-within works

:focus-within matches an element when it or any element inside it has focus. Click or tab into the search box in the preview and the whole box gets the highlight, not just the input. Tab on to the Clear button and it stays highlighted, because focus is still inside the wrapper. Tab out and it goes away.

Compare that with :focus, which matches only the focused element itself. For a field with a label and a hint, :focus-within lets you color the label too. For a dropdown, it keeps the menu open while a keyboard user tabs through its items, which :hover alone can't do.

Keep focus visible

These examples remove the input's own outline because the wrapper shows focus instead. Never remove an outline without a replacement: WCAG 2.4.7 asks for a visible focus indicator. Everything runs in your browser and nothing is uploaded.

Frequently asked questions

What is :focus-within?

A CSS pseudo-class that matches an element when it, or anything inside it, has focus. Use it to style a whole search box, form field or menu while someone types or tabs inside it.

What's the difference between :focus and :focus-within?

:focus matches only the element that has focus, such as the input itself. :focus-within also matches every ancestor of that element, so a wrapper can light up while its input, button or link is focused.

How do I show it only for keyboard users?

Use :has(:focus-visible) on the wrapper instead of :focus-within. :focus-visible matches when the browser decides a focus ring should show, which is usually keyboard focus, not a mouse click. Browsers treat any focus on a text input as visible, so the difference shows on buttons.

Is it safe to remove the input's outline?

Only when the wrapper shows a clear focus style instead, as these examples do. WCAG 2.4.7 (Focus Visible, Level AA) asks for a visible focus indicator for keyboard users.

Does it upload my input?

No. The preview runs entirely in your browser, and it keeps working offline once the page has loaded.

Take it further
Developer Tools

Practical utilities for front-end design and implementation work.

Learn more