css · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Combinators make :has() precise: > and +.
A is the symbol between two selectors that says how the elements are related. You know the space: anywhere inside. The , >, means directly inside, so .card:has(> img) only counts images that are the card's own children.
The , +, means straight after, in the same parent. h2:has(+ p) styles a heading that is followed right away by a paragraph.
Mix in :nth-child to count: ul:has(> li:nth-child(4)) matches lists with four items or more, so long lists can change their layout.
<h2>Opening hours</h2>
<p>Monday to Friday, 9 till 5.</p>
<h2>Find us</h2>
<ul>
<li>12 Mill Lane</li>
</ul> h2:has(+ p) {
margin-bottom: 4px;
color: #0f766e;
} Press show my page to see it here.
guess first
Two lists, one rule. Which list changes?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<ul class="short">
<li>Tea</li>
<li>Coffee</li>
</ul>
<ul class="long">
<li>Eggs</li>
<li>Milk</li>
<li>Flour</li>
<li>Sugar</li>
</ul> ul:has(> li:nth-child(4)) {
columns: 2;
background-color: #fde68a;
}
your turn
Your turn. Tuck headings onto their subtitles.
Fill in the combinator so only a heading followed straight away by a .subtitle loses its bottom margin.
the page you’re styling
<h2>Spring menu</h2>
<p class="subtitle">Served from March</p>
<h2>Drinks</h2>
<p>Ask at the bar.</p>your css
Press show my page to see it here.
- the Spring menu heading hugs its subtitlenot checked yet
- the Drinks heading keeps its marginnot checked yet
fix it
Both cards lost their padding. Can you fix it?
the page you’re styling
<div class="card">
<img src="tree.svg" alt="An oak tree">
<p>Ancient oaks</p>
</div>
<div class="card">
<p class="author"><img src="cat.svg" alt="">By Pickles</p>
</div>your css
Press show my page to see it here.
- the photo card has no paddingnot checked yet
- the author card keeps its paddingnot checked yet
- The second card only holds a tiny avatar, deep inside a paragraph. Why does it still pass the test?
- With no combinator,
:has(img)looks anywhere inside. You only want images that are the card's own children. - Use the child combinator,
.card:has(> img), then press run.
nailed it
you made :has() look in exactly one place. :D
>means directly inside;+means straight after.:has(> img)ignores images buried deeper.- Put
:nth-childinside:has()to count items.
new words in your collection
- combinator
- child combinator
- next-sibling combinator
This lesson isn’t saved. A free account remembers every lesson you finish.