Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.2 — :has() in Practice
CSS · Example 3 of 3

A checkbox that changes the whole page

The checkbox is not an ancestor of the items, but .page:has(#compact:checked) turns the page into the subject, and the descendant .item follows. Click the checkbox to toggle it yourself.

:has() matches an element when something inside it, or after it, matches the selector you give; that lets CSS style a form from the state of its inputs, a parent from its children, and a list from how many items it has, all without JavaScript.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write CSS that gives a <figure> a grey background only when it contains a <figcaption>.

02

Write CSS so a .plan label gets a 2px indigo border when the radio button inside it is checked.

03

Write a quantity query that makes a .tags list display as a single flex row when it has 3 or fewer items.

Explain it without notes

01

What does :has() do, and which element does a selector like .card:has(img) style?

02

Show how :has() can style a form based on its inputs' state, and why :user-invalid is better than :invalid for error styles.

03

Explain a quantity query that matches lists with at least 4 items and one that matches exactly 3 items.

04

What are the restrictions and the specificity rules of :has()?

A checkbox that changes the whole page

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

normal padding-top: 14px
compact padding-top: 4px