Rikard
Rikard

Reputation: 7805

Element changes place when position fixed applied

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/

Upvotes: 0

Views: 47

Answers (2)

Karim AG
Karim AG

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

Unamata Sanatarai
Unamata Sanatarai

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';
});

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

Upvotes: 1

Related Questions