Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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').style.top = "50%";
document.getElementById('block').style.transform = "translate(50%, 50%)";

http://jsfiddle.net/JFqus/2/

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>

http://jsfiddle.net/ZazmC/

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

http://jsfiddle.net/ZazmC/1/

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


Solution 2:

use element.style.cssText, for example:

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

works in all browsers you likely care about: http://www.quirksmode.org/dom/w3c_css.html#t30


Post a Comment for "How Do I Positioning A Div Based Upon Percentages With CSS"