<!DOCTYPE html> <html lang="en"> <head> <title>Vertical Centering with Equal Top and Bottom Padding</title> <meta charset="utf-8"> <meta name="description" content="" /> <style type="text/css"> #parent { background: #ccc; } /* horizontal centering */ #parent { width: 400px; margin: 20px auto; } .child { text-align: center; background: #999; color: #fff; } /* vertical centering */ #parent { padding: 5% 0; } .child { padding: 1% 0; } body { margin: 0px auto; background-color: beige; } </style> </head> <body> <form> <div id="parent"> <div class="child">用户 <input type="text" /></div> <div class="child">密码 <input type="text" /></div> <div class="child"></div> <div class="child" style="background: #ccc;"> <input type="submit" value="登录" style="80px;" /></div> </div> </form> <script type="text/javascript"> var p = document.getElementById("parent"); resize_fn = function (e) { var zbody_height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight); var zdiv_height = Math.max(p.scrollHeight, p.clientHeight); var ztop = (zbody_height - zdiv_height) / 2; p.style.marginTop = ztop + "px"; }; //var w = document.getElementsByClassName("child"); var w = document.querySelectorAll(".child"); for (var i = 0; i < w.length;i++) { var oi = w.item(i); oi.style.background = "#ccc"; } //p.style.background = "beige"; resize_fn(); document.body.onresize = resize_fn; </script> </body> </html>