liveBook · Manning

Focus-within pseudo-class

As explained in Tiny CSS Projects

The focus-within pseudo-class matches an element when it or one of its descendants has focus.

A summary card can keep its heading visible while hiding its description and link until someone interacts with it. Hover can reveal the content for a pointer user, but a keyboard user may reach the hidden link without hovering. The link is still in the document and can receive focus even though it is visually hidden. section 5.5

`:focus-within` lets the card respond when a link inside it receives focus. In `section:focus-within div`, the rule styles the card’s inner `div` when focus is within the `section`. Pairing it with `section:hover div` gives pointer hover and descendant focus the same reveal effect. section 5.5 section 1.6.3

Listing 5.17 Showing content on hover and focus-within
@media (hover: hover) and (min-width: 700px) and
 (prefers-reduced-motion: no-preference) {
 main > section > div {
  transform: translateY(calc(350px - 8rem));
  height: 5rem;
  overflow: hidden;
  transition: all 700ms ease-in-out;       #1
 }
 div > *:not(h2) {
  opacity: 0;
  transform: translateY(1rem);
  transition: all 700ms ease-in-out;       #1
 }
 section:hover div,                        #2
 section:focus-within div {                #3
  transform: translateY(0);
  height: calc(350px - 4rem);
 }
 
 section:hover div > *:not(h2),            #4
 section:focus-within div > *:not(h2){     #5
  opacity: 1;
  transform: translateY(0);
 }
}

The card starts with a shortened inner container and transparent, displaced nonheading content. Matching `:hover` or `:focus-within` restores the container’s position and height, then makes the description and link visible. `transition` animates the change. section 5.5

The hiding and reveal rules sit inside a media query requiring hover support, a minimum width of 700px, and no reduced-motion preference. When those conditions are not met, this interaction does not hide the card content. That keeps the reveal effect from being necessary on layouts where its conditions do not apply. section 5.5 section 5.6

How Tiny CSS Projects covers it

How deep it goes
Defines descendant-triggered styling and works through the card’s reveal rules; does not examine selector internals.
Examples
Uses a summary card whose hidden description and link reappear on hover or when the link gains focus.
What it assumes
Introduces focus and pseudo-class states alongside link selectors, then uses CSS selectors and a focusable link in the card example.
What you can do after
Build it from scratch as a CSS reveal interaction that responds to both pointer hover and keyboard focus.
How it connects
Connects :focus-within to :focus, :hover, :not(), transitions, media queries, and prefers-reduced-motion.

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.