Reputation: 309
I'm struggling for a while positioning a div at 100px from the imaginary center of the window.
My code is doing: middle window / 2 + 100px and is not what I want:
var middle = screen.availWidth/2;
var position = middle+300;
document.getElementById('bookmarks').style.left = position + 'px';
Using this code my DIV is going left and right based on the window size and I wanted it to be at 100 px from the center not moving at all.
Also I know this is depending on browser.
Any help with this?
Thanks! Vic
Upvotes: 0
Views: 359
Reputation: 4517
You say middle but you do not say on which axis, so assuming that you want the middle of both x and y you could use the following code. Note: it is factoring the 200px width and height for the div.
<body>
<div style="background-color: #000000; height: 200px; width: 200px; position: fixed;" id="bookmarks"></div>
<script>
var middleX = window.innerWidth/2;
var middleY = window.innerHeight/2;
var positionX = middleX-100;
var positionY = middleY-100;
document.getElementById('bookmarks').style.left = positionX + 'px';
document.getElementById('bookmarks').style.top = positionY + 'px';
</script>
</body>
Also note that there are cleaner ways of doing this. I left it like this so that you can understand the logic and then clean it yourself later and you also said that you did not want it moving at all so I assumed that you wanted position:fixed.
Upvotes: 2