I am trying to fix a div so it always sticks to the top of the screen, using:
position: fixed;
top: 0px;
right: 0px;
However,
Actually this is possible and the accepted answer only deals with centralising, which is straightforward enough. Also you really don't need to use JavaScript.
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute, but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
For example:
/* Main site body */
.wrapper {
width: 940px;
margin: 0 auto;
position: relative; /* Ensure absolute positioned child elements are relative to this*/
}
/* Absolute positioned wrapper for the element you want to fix position */
.fixed-wrapper {
width: 220px;
position: absolute;
top: 0;
left: -240px; /* Move this out to the left of the site body, leaving a 20px gutter */
}
/* The element you want to fix the position of */
.fixed {
width: 220px;
position: fixed;
/* Do not set top / left! */
}
Content in here will be fixed position, but 240px to the left of the site body.
Sadly, I was hoping this thread might solve my issue with Android's WebKit rendering box-shadow blur pixels as margins on fixed position elements, but it seems it's a bug.
Anyway, I hope this helps!