46

I created a div element, that I placed all the way on the right of my site. The only problem is that its at the top of the site, so if i scroll down it remains there.

How can I force it to remain in the same part of the page, when page is being scrolled?

This is, what I've managed to figure out myself so far:

<div style="width: 200px; background-color: #999; z-index: 10; position: absolute; right: 0; top: 0; height: 83px;">
</div>
trejder
  • 17,148
  • 27
  • 124
  • 216
soniccool
  • 5,790
  • 22
  • 60
  • 98
  • possible duplicate of [How do I make a
    move up and down when I'm scrolling the page?](http://stackoverflow.com/questions/1638895/how-do-i-make-a-div-move-up-and-down-when-im-scrolling-the-page)
    – Lucas Apr 11 '14 at 02:17
  • 1
    There's a new feature in CSS that bakes this functionality in automatically without javascript: `position: sticky`. https://caniuse.com/#feat=css-sticky – Randolpho Nov 14 '18 at 17:34
  • Just tried sticky, and it doesn't seem to be working yet in Chrome as of 2/11/2020. – eidylon Feb 11 '20 at 16:21

6 Answers6

93

Change position:absolute to position:fixed;.

Example can be found in this jsFiddle.

inquisitive
  • 3,738
  • 6
  • 30
  • 56
Anton D
  • 1,336
  • 1
  • 12
  • 18
  • 8
    The problem with the ```position: fixed``` is that it gets out of the flow, and things are going to overlap themselves. – Csibi Norbert Aug 07 '20 at 11:50
11

Use position: fixed instead of position: absolute.

See here.

trejder
  • 17,148
  • 27
  • 124
  • 216
user2769260
  • 111
  • 3
9

You can do this replacing position:absolute; by position:fixed;.

SeniorJD
  • 6,946
  • 4
  • 36
  • 53
SOULAT TOQEER
  • 91
  • 1
  • 3
4

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

Debu Shinobi
  • 2,057
  • 18
  • 21
2
  1. You can use position : absolute and adjust the alignment using css parameters like below.
.dvfixed{
  position: absolute;
  left: 100px;
  right: 10px;
  bottom: 5px;
  top: 5px;
}

OR

  1. you can use float like below.
.dvfloat{
  float:right;
}
0

i my case the blue line I want it to stay fixed, i used sticky with right 0 and left 0

enter image description here