代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
position: absolute;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div></div>
<script>
var box = document.querySelector('div');
var clientW = document.documentElement.clientWidth;
var clientH = document.documentElement.clientHeight;
var boxW = box.offsetWidth;
var boxH = box.offsetHeight;
box.style.left = (clientW - boxW) / 2 + 'px';
box.style.top = (clientH - boxH) / 2 + 'px';
</script>
</body>
</html>
运行结果