Command Palette

Search for a command to run...

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

Parent styling and quantity queries

Delete the image from the first card and run again: it stops being a grid and gets the dashed border. Add a 4th item to the last list and it loses teal and gains two columns.

: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()?

Parent styling and quantity queries

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

card 1 display: grid
card 2 border-style: dashed
2 items, columns: auto
5 items, columns: 2
exactly 3, colour: rgb(0, 128, 128)