<!DOCTYPE html><html><head><meta charset=’utf-8‘> <style> html, body{position:relative;width:100%;height:100%} div{position:absolute; width:200px;height:200px} </style> <head><body> <div>Hello World</div> <body></html> <script>
function $(tag){return document.querySelector(tag)}
function center(chi,par,typ)
{
x = (par.clientWidth-chi.clientWidth)/2+‘px‘; y = (par.clientHeight-chi.clientHeight)/2+‘px‘; chi.style.left=typ==‘tb‘?chi.offsetLeft+‘px‘:x; chi.style.top=typ==undefined?chi.offsetTop+‘px‘:y; };
center($(‘div‘),$(‘body‘)) </script>
不填(undefined) --- 左右居中 ‘tb‘ - 上下居中 其他任意字符如‘‘ -- 全局中
window.onresize=function() { // 再执行一遍 center($(‘div‘),$(‘body‘)) }
原文:https://www.cnblogs.com/tacty/p/12299574.html