css · level 3 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
queries style a component by the space it is given.
Media queries ask how wide the screen is. But a card in a narrow sidebar and the same card in a wide main column share one screen. A asks how wide the card's container is instead.
Give the parent container-type: inline-size and it becomes a container. Then @container (min-width: 300px) { … } styles what is inside it whenever that container is at least 300px wide.
Now one component works anywhere: it fits its slot, not the device.
<div class="slot wide"><div class="card"><b>Pickles</b><span>Cat, 3</span></div></div>
<div class="slot narrow"><div class="card"><b>Rex</b><span>Dog, 5</span></div></div> .slot {
container-type: inline-size;
}
.wide {
width: 400px;
}
.narrow {
width: 200px;
}
@container (min-width: 300px) {
.card {
display: flex;
gap: 12px;
}
} Press show my page to see it here.
guess first
Two boxes, one rule. Which message turns teal?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<div class="box big"><p class="msg">Big box</p></div>
<div class="box small"><p class="msg">Small box</p></div> .box {
container-type: inline-size;
}
.big {
width: 360px;
}
.small {
width: 180px;
}
@container (min-width: 250px) {
.msg {
color: teal;
}
}
your turn
Your turn. Let the product card adapt.
Fill in the blanks: make .slot a container, then lay the card out in a row when its container is at least 320px wide.
the page you’re styling
<div class="slot">
<div class="product"><img src="ball.svg" alt="A football"><p>Match ball, £25</p></div>
</div>your css
Press show my page to see it here.
- the slot is a containernot checked yet
- the card becomes a rownot checked yet
- the query tests for 320pxnot checked yet
fix it
The card never changes, however wide its slot. Can you fix it?
the page you’re styling
<div class="slot">
<div class="card"><b>Ava</b><span>Designer</span></div>
</div>your css
Press show my page to see it here.
- the card turns into a rownot checked yet
- the slot is the containernot checked yet
- A container query styles what is inside a container. Which element is the card inside?
- An element cannot query its own size. The card needs its parent to be the container.
- Move
container-type: inline-size;from.cardto.slot, then press run.
nailed it
you built a card that fits any slot. :D
container-type: inline-sizemakes a container.@containertests the container's width, not the screen's.- An element cannot query itself, only a container around it.
new words in your collection
- container query
- container
This lesson isn’t saved. A free account remembers every lesson you finish.