<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; } #wrap { width: 500px; height: 500px; background: grey; //新版本flex方法 display: flex; justify-content: center; //主軸 align-items: center; //側軸 //舊版本的flex版本 display: -webkit-box; -webkit-box-pack: center; //主軸 -webkit-box-align: center;//側軸 // position: relative; } #box{ width: 200px; height: 200px; background: deeppink; position: absolute; //第一種垂直居中法 top: 0; left: 0; bottom: 0; right: 0; margin: auto; //第二種垂直居中法 top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; //第三種垂直居中法 top: 50%; left: 50%; transform: translate(-50%,-50%); } </style> </head> <body> <div id="wrap"> <div id="box"></div> </div> </body> <script type="text/javascript"> window.onload = function () { var box = document.getElementById('box'); } </script> </html>