0

When I apply position: fixed with Javascript my element moves a few pixels down and gets fixed in another position, some pixels down, instead of just staying where is was.

Why is this?

// html
<div id="container">
    <div id="myDiv"></div>
</div>

// CSS
#container {
    height: 2000px;
}
#myDiv {
    margin-top: 50px;
    width: 100px;
    height: 50px;
    background-color: #88a;
}

// Javascript
myDiv.style.position = 'fixed';

I find this behaviour at least in Chrome and FF.

http://jsfiddle.net/bSM8h/

Rikard
  • 7,485
  • 11
  • 55
  • 92

2 Answers2

1

When you apply position:fixed, also do:

pin.addEventListener('click', function () {
    myDiv.style.position = 'fixed';
    myDiv.style.top = '50px';
    myDiv.style.marginTop = '0';
});

http://jsfiddle.net/bSM8h/2/

*edit*

By default browsers do body{padding:5px;} that is why a good idea is to html5boilerplate your css's

*end edit*

For some reason (see explanation here), margin-top also pushed the container with it. Once applied position:fixed, the container sprung back to the top of the page (lost the margin) and was positioned 5px from the top of page.

before position:fixed

enter image description here

after position:fixed

enter image description here

Community
  • 1
  • 1
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
  • Thank you for your feedback. Yes I am most interested in the "_For some reason_" part you mentioned. This problem does not happen when I reset the body for example: http://jsfiddle.net/bSM8h/3/ – Rikard Apr 27 '14 at 06:05
  • 100% on the nose! :) By default body has a `padding of 5px`. So the #container is positioned 5px from the top of page (see img2). That's why its ALWAYS a good idea to use `normalize/reset css` – Unamata Sanatarai Apr 27 '14 at 06:07
1

Just add this to your CSS:

body {
    margin:0;
    padding:0;
}

This will prevent the extra padding added by the browser defaults.

Karim AG
  • 2,166
  • 15
  • 29