Fixed Position

An element with position: fixed is taken out of normal flow, just like an absolute one. Its offsets, however, are always measured from the edges of the browser window, not from the page or from an ancestor. That is why it stays in the same place on the screen, even when you scroll the page.

We use fixed position for things that should always be at hand: a button that takes you back to the top, a chat button, or a bar with a message at the bottom of the window.

At the end of the cat page, we've added a link that takes you back to the top:

<a href="#" class="to-top">Back to top</a>

As you know from the HTML course, a link to # scrolls the page all the way up. In the stylesheet, we've made the link look like a button.

So that you can try scrolling, we've also made the page taller: in the rule for body, min-height: 200vh says that the page must be at least twice as tall as the window. The property min-height sets the minimum height: unlike height, it lets the element grow taller if its content needs more space.

Instructions

First, try absolute position. In the rule for .to-top, add position: absolute, bottom: 20px and right: 20px. The link moves to the bottom right corner of the preview. Now scroll the page down: the link scrolls away with it. When no ancestor has a position, absolute offsets are measured from the first screen of the page (an area as big as the window at the very top of the page), not from the window itself.

Now change absolute to fixed. Scroll the page again: the link stays in the corner of the window the whole time. Click it, and the page scrolls back to the top.

Start programming for free

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

Or sign up with:

8/10