How do I positioning a div based upon percentages with CSS

I'm looking for help with positioning an object along X, and Y coordinates based upon percentage in order to allow it to move on top of everything when you scroll around the page. The numbers are working, but the CSS seems to be confused, so all I need is alignment help.

Currently I have:

document.getElementById('block').style.display="style='position: absolute; left: place%; top: place%; transform: translate(place%, place%);'";

Example: office applications moving tool bars around when they snap off the toolbar holder, and sit there

The fiddle is:



You are attempting to set multiple values in one line, this isn't possible.

document.getElementById('block').style.position = "absolute";
document.getElementById('block').style.left = document.getElementById('block') = "50%";
document.getElementById('block').style.transform = "translate(50%, 50%)";

If you just want the styles to be applied all the time, you can add it right into the div's style attribute:

<div id="block" style="background-color:#000000;height:100px;width:100px;position: absolute; left: 50%; top: 50%; transform: translate(50%, 50%);"></div>

But this is ugly, you should separate styles from markup:

#block {
    background-color: #000000;
    height: 100px;
    width: 100px;
    position: absolute;
    left: 50%; top: 50%;
    transform: translate(50%, 50%);

Also, I think you want position: fixed, not absolute.


use, for example:

document.getElementById('block').style.cssText = 'position: absolute; /* ... */';

works in all browsers you likely care about:


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.