Sticky Position

The last value of position is sticky. A sticky element is a mix of a relative and a fixed one. At first, it behaves like a relative element: it's in normal flow and scrolls with the page. But as soon as scrolling would carry it past the edge given by its offset, for example top: 0, it sticks to that edge of the window and stays there, like a fixed element.

A sticky element never leaves its parent, though. It sticks only while its parent is on the screen: when the end of the parent scrolls past, the sticky element is pushed away together with it. Try it in this box. Both headings in it have position: sticky and top: 0, and each of them is in its own section. The box scrolls on its own, so the headings stick to its top edge instead of the top of the window:

Section A

Scroll down inside this box.

The heading of section A sticks to the top.

It stays there while section A is visible.

Keep scrolling...

This is the last line of section A.

Section B

Section A has scrolled away, and its heading went with it.

Now the heading of section B sticks to the top.

Its parent is section B.

Keep scrolling...

This is the end of the box.

Without an offset (top, bottom, and so on), a sticky element doesn't stick at all.

Sticky position is often used for navigation that stays at the top of the window while you scroll. Unlike a fixed element, a sticky one keeps its place in normal flow, so at the start of the page, it doesn't cover the content below it.

And when elements overlap, which one is on top? Elements with a position other than static are drawn over the static ones, and among themselves in the order in which they are in the HTML: a later one covers an earlier one. We can change this with the property z-index, which works on elements whose position isn't static: an element with a higher z-index covers one with a lower value. Elements without a z-index behave as if it were 0.

Instructions

In the rule for nav, add position: sticky and top: 0. Scroll the page: the navigation stays at the top of the window. Its parent is body, which spans the whole page, so the navigation never scrolls away.

Scroll down to the breed cards: they slide over the navigation instead of under it. They have position: relative and they come after the navigation in the HTML, so they're drawn on top of it. In the rule for nav, add z-index: 1. Now the cards slide under the navigation.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

9/10

Next