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 con JS</title>
</head>
<body>
    <div id = "foo"></div>
</body>
</html>
 
html{
    width: 100%;
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
}
#foo{
    width: 30%;
    height: 30%;
    background: red;
    position: absolute;
}
 
var div = document.querySelector("#foo"),
    divWidth, divHeight, winWidth, winHeight,
    centrar = function(){
        divWidth = parseInt(getComputedStyle(div).width);
        divHeight = parseInt(getComputedStyle(div).height);
        winWidth = this.innerWidth;
        winHeight = this.innerHeight;
        
        div.style.top = (((winHeight / 2) - (divHeight / 2)) + this.scrollY) + "px";
        div.style.left = (((winWidth / 2) - (divWidth / 2)) + this.scrollX) + "px";
    };
window.addEventListener("load", centrar, false);
window.addEventListener("resize", centrar, false);
Output 300px

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

Dismiss x
public
Bin info
Alexis88pro
0viewers