liveBook · Manning

Focus pseudo-class

As explained in Tiny CSS Projects

The CSS :focus pseudo-class matches an element whenever it has focus, regardless of the input method that caused the focus.

The CSS `:focus` pseudo-class matches an element while it has focus. A focusable element typically gains focus when clicked; keyboard navigation also moves focus among links, buttons, and form fields. The selector works regardless of which interaction caused the focus. section 1.6.3

Make a card link easy to find

A card link can keep its bright background for its usual appearance and gain an outline when focused: `a:focus { outline: 1px dashed #e69500; outline-offset: 3px; }`. The offset separates the dashed outline from the link. section 5.4.2

Listing 8.4 Button hover and focus states
button:hover,
.button:hover {
  outline: dotted 1px #2c6c69;
  outline-offset: 2px;
}
 
button:focus,
.button:focus {
  outline: solid 1px #2c6c69;
  outline-offset: 2px;
}

Compare the cart controls’ dotted hover outline with their solid focus outline. The same focus rule covers both buttons and links styled as buttons. section 8.2.2

Keep a visible focus style when customizing interactive controls: it helps make the design accessible. Use `:focus-visible` instead when the style should appear for keyboard interaction rather than every way of gaining focus. Use `:focus-within` to style a parent while a child has focus. section 10.11 section 1.6.3

How Tiny CSS Projects covers it

How deep it goes
Defines focus and works through outline rules for links and buttons, without detailing browser focus internals.
Examples
Shows a dashed outline on a card link and a solid outline on checkout-cart links and buttons.
What it assumes
Introduces focus behavior while assuming basic familiarity with HTML links, buttons, and CSS rules.
What you can do after
Practice/perform focus styling by adding visible CSS outlines to links and buttons.
How it connects
Connects focus styling to hover, keyboard navigation, accessibility, :focus-visible, and :focus-within.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny CSS Projects. The section links point to the parts of the book it draws on.