Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Centrar</title>
</head>
<body>
    <div id = "foo"></div>
</body>
</html>
 
html, body{
    width: 100%;
    height: 100%;
}
#foo{
    width: 25%;
    height: 25%;
    background: red;
}
 
function centrar(){
    var elem = document.getElementById("foo"),
        elemWidth = elem.offsetWidth,
        elemHeight = elem.offsetHeight,
        winWidth = window.innerWidth,
        winHeight = window.innerHeight,
        winX = window.scrollX,
        winY = window.scrollY;
        
    elem.style.marginTop = (winHeight / 2 - elemHeight / 2) + winY + "px";
    elem.style.marginLeft = (winWidth / 2 - elemWidth / 2) + winX + "px";
}
document.addEventListener("DOMContentLoaded", centrar, false);
window.addEventListener("scroll", centrar, false);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
Alexis88pro
0viewers