css · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
:first-child, :last-child and count siblings.
A is an element that shares a parent with another, like the <li> items in one list. Some pseudo-classes pick siblings by position: li:first-child is the first, and li:last-child is the last.
:nth-child() takes a number or a pattern. li:nth-child(3) is the third. odd and even pick every other one, perfect for striped rows, and 3n picks every third.
They count every sibling, whatever its tag, and they start counting from 1, not 0.
<ul>
<li>Pickles: 120 points</li>
<li>Rex: 95 points</li>
<li>Luna: 90 points</li>
<li>Mango: 70 points</li>
<li>Biscuit: 45 points</li>
</ul> li:nth-child(odd) {
background-color: whitesmoke;
}
li:first-child {
font-weight: bold;
} Press show my page to see it here.
Try li:nth-child(3n) in the first rule and only the third item gets the background.
guess first
li:nth-child(2) turns blue. Which item is it?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<ul>
<li>Pickles</li>
<li>Rex</li>
<li>Luna</li>
<li>Mango</li>
</ul> li:nth-child(2) {
color: blue;
}
your turn
Your turn. Stripe the list.
Give every even item a background colour of your choice, so the list has stripes and the odd items stay plain.
the page you’re styling
<ul>
<li>Milk</li>
<li>Bread</li>
<li>Eggs</li>
<li>Apples</li>
<li>Cheese</li>
<li>Rice</li>
</ul>your css
Press show my page to see it here.
- the even items have a backgroundnot checked yet
- the last item is striped toonot checked yet
- the odd items stay plainnot checked yet
fix it
The last item should have no line under it. Fix it!
the page you’re styling
<ul>
<li>Wake up</li>
<li>Feed the cat</li>
<li>Make toast</li>
</ul>your css
Press show my page to see it here.
- the last item has no linenot checked yet
- the other items keep theirsnot checked yet
- The browser skipped the second rule. Look closely at its pseudo-class.
- There is no
:last. The pseudo-class has a longer name. - Change it to
li:last-child, then press run.
nailed it
you counted children like a pro. :D
:first-childand:last-childpick the ends.:nth-child(odd)and:nth-child(even)make stripes.- CSS counts siblings from 1, not 0.
new words in your collection
- sibling
- nth-child
This lesson isn’t saved. A free account remembers every lesson you finish.