css · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
keeps a box in view as you .
When a page is too long for the screen, you scroll it. A sticky box scrolls along with the page until it reaches its offset. Then it stays stuck there.
position: sticky with top: 0 makes a header that sticks to the top of the screen. Without an offset, sticky does nothing at all.
A sticky box only sticks inside its parent. When the parent scrolls away, the sticky box goes with it. Give it a background, or the words underneath show through.
<div class="header">The Daily Paw</div>
<p class="story">Scroll down: the header stays at the top while this long story slides underneath it.</p> .header {
position: sticky;
top: 0;
padding: 12px;
border-bottom: 1px solid silver;
background-color: white;
}
.story {
height: 900px;
} Press show my page to see it here.
Scroll inside the preview to watch the header stay put.
guess first
Sticky titles inside cards. How long does each one stick?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<div class="card">
<h2 class="title">Pets</h2>
<p>Cats, dogs and a very old tortoise.</p>
</div>
<div class="card">
<h2 class="title">Plants</h2>
<p>Ferns, cacti and one sunflower.</p>
</div> .title {
position: sticky;
top: 0;
background-color: white;
}
.card {
height: 500px;
}
your turn
Your turn. Stick the menu bar.
Make the menu bar sticky, with a top offset that keeps it at the top of the screen as the page scrolls.
the page you’re styling
<div class="bar">Home · Shop · Help</div>
<div class="content">Lots of shopping to scroll past.</div>your css
Press show my page to see it here.
- the bar is stickynot checked yet
- the bar has a top offsetnot checked yet
fix it
The header refuses to stick. Fix it!
the page you’re styling
<div class="header">Recipes</div>
<div class="list">Pancakes, waffles, crumpets and more.</div>your css
Press show my page to see it here.
- the header is stickynot checked yet
- the header has a top offsetnot checked yet
- The position is right. What else does sticky need?
- Without an offset, a sticky box never knows where to stop.
- Add
top: 0;to.header, then press run.
nailed it
your header stays in sight. :D
position: stickyplustopkeeps a box in view.- Without an offset, sticky does nothing.
- A sticky box only sticks inside its parent.
new words in your collection
- scroll
- sticky
This lesson isn’t saved. A free account remembers every lesson you finish.