How to make an element follow the scrollbar?

December 20, 2021

How to make an element follow the scrollbar?

In this article you will learn how to make an element follow the scrollbar with CSS only, for you to use in your web projects!

make an element follow the scrollbar cover

What’s up programmer, okay? Let’s learn something new!

The idea behind leaving an element with the scrollbar

is leaving it with the position rule as fixed

This way, the element is fixed on the screen and respects any position imposed by CSS rules

So then we adjust its top, left, right or bottom

The way the layout asks for the element to be

Let’s go to a practical example:

<!DOCTYPE html>
  <title>Fixed element</title>
  <meta charset="utf-8">
  <div id="fixed"></div>

Here we have a simple web page, with an element that will stay on the screen

Now let’s go to the CSS that will position it:

body {
 height: 3000px;

#fixed {
 position: fixed;
 right: 50px;
 top: 200px;
 background-color: gold;
 border: 1px solid red;
 width: 100px;
 height: 100px;

Note that the trick only occurs in the first 3 lines of #fixed, position as fixed and a rule for right and top, which are the positions of the element on the screen

Then we style the element with a background color, height and width, so that it appears, but this is not necessary.

We left the body with a big height too, so the page has a scrollbar, it’s not necessary

See how it looks in the browser:

fixed element example

Note that the page is not positioned at the top (see scroll bar)

And the element is still present, that is, it is following the scroll bar

And so, we have our problem solved! 


In this article, we learned  how to make an element follow the scrollbar

We use position fixed, to make the element fixed on the screen, with instructions for right and top, to also leave it positioned on the right side of the screen

The element’s position must be according to the layout, the only rule needed is position with fixed

Want to learn more about HTML and CSS? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x