Course contentsShow
← Web Development
Lesson 448 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

:focus-within for Container Highlighting

Apply styles to parent elements when any descendant receives focus, useful for form groups and search boxes.

:focus-within for Container Highlighting

What you'll learn: How to highlight entire containers when any child element inside them receives focus.

The Core Idea

The :focus-within pseudo-class lets you style a parent element when any descendant inside it gets focus. Think of it like a "ripple effect" — when someone clicks or tabs into an input field, the entire form group or container lights up to show where attention is focused.

Without :focus-within, you could only style the focused element itself. With it, you can create visual context by highlighting the whole surrounding area.

Why This Matters

Imagine a search box inside a container, or a group of form inputs wrapped in a <div>. When a user focuses on the input, you might want to:

  • Add a border or shadow to the parent container
  • Change the background color of the entire form group
  • Highlight labels or related content nearby

This improves usability by making it crystal clear which section of the page is active.

How It Works

The syntax is straightforward:

.search-container:focus-within {
  border: 2px solid blue;
  box-shadow: 0 0 8px rgba(0, 0, 255, 0.3);
}

.form-group:focus-within {
  background-color: #f0f8ff;
}

When any element inside .search-container or .form-group receives focus (like an <input> or <button>), the container itself gets these styles applied.

Real-World Example

A form group with a label and input: when you click the input, the entire group highlights, making the relationship between label and field obvious.

Key Takeaway: :focus-within applies styles to a parent when any child gains focus, perfect for highlighting form groups, search containers, and improving visual feedback during navigation.