How do I positioning a div based upon percentages with CSS

自闭症网瘾萝莉.ら 提交于 2019-12-13 08:13:15

问题


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: http://jsfiddle.net/JFqus/


回答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.




回答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



来源:https://stackoverflow.com/questions/23438552/how-do-i-positioning-a-div-based-upon-percentages-with-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!