40

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
  • 16,472
  • 26
  • 116
  • 210
soniccool
  • 5,276
  • 21
  • 58
  • 96
  • 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

5 Answers5

82

Change position:absolute to position:fixed;.

Example can be found in this jsFiddle.

inquisitive
  • 3,558
  • 6
  • 26
  • 54
Anton D
  • 1,226
  • 1
  • 12
  • 18
  • 7
    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
9

Use position: fixed instead of position: absolute.

See here.

trejder
  • 16,472
  • 26
  • 116
  • 210
7

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

SeniorJD
  • 6,515
  • 4
  • 33
  • 51
SOULAT TOQEER
  • 71
  • 1
  • 2
2

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
  • 1,358
  • 13
  • 18
1
  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;
}