Reputation: 7805
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.
Upvotes: 0
Views: 47
Reputation: 2193
Just add this to your CSS:
body {
margin:0;
padding:0;
}
This will prevent the extra padding added by the browser defaults.
Upvotes: 1
Reputation: 6637
When you apply position:fixed
, also do:
pin.addEventListener('click', function () {
myDiv.style.position = 'fixed';
myDiv.style.top = '50px';
myDiv.style.marginTop = '0';
});
*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
after position:fixed
Upvotes: 1