Fixed

Fixed positioning places an element relative to the browser window, so it stays on screen while the page scrolls.

Apprentice · CSS · Updated

By

After this lesson you can

  • Keep an element in the same spot on screen while the page scrolls with fixed positioning

Key takeaways

  • Fixed positioning places an element relative to the browser window, measured from the window's top left corner.
  • A fixed element stays in the same spot on screen while the rest of the page scrolls.
  • The space it would have used isn't kept, so the elements after it move up into that space.

fixed position places an element relative to the browser window (the viewport), measured from its top left corner, so it stays in the same spot on screen while the page scrolls. The space it would have used is not kept.

.div-2 {
    position: fixed;
    left: 30px;
    top: 30px;
}

Div 2 placed 30px from the window's top left corner, over div 1, and div 3 moved up into the space div 2 left

As the page is scrolled, fixed divs do not scroll.

After scrolling, div 2 is still 30px from the top of the window while divs 3, 4 and 5 scroll up underneath it

Do it: keep Back to top on screen

Your reading list has grown long, and the Back to top link sits at the very bottom, where nobody sees it. It should stay in the window's bottom right corner the whole time, while the rest of the page scrolls under it.

Here is where it should be:

What The value
Measured from the browser window, not the page
Above the window's bottom edge 16px
In from the window's right edge 16px
While the page scrolls the link stays put; everything else scrolls

Your job: write one rule for the Back to top link, class to-top.

  • Keep it in the same spot in the window while the page scrolls.
  • Put it 16px above the window's bottom edge and 16px in from its right edge.
  • Leave everything else on the page as it is, so it scrolls as usual.

Practiced live on the lesson page: write the CSS right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Chat buttons, cookie notices and navigation bars that never leave the screen are fixed elements.

Key terms

Cheat sheets