- 拿来即食
<!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>
- center()的typ参数
不填(undefined) --- 左右居中 'tb' - 上下居中 其他任意字符如'' -- 全局中
- 补充说明: 子标签必须为absolute,父标签position必须非默认值; 非响应式居中,响应式要补充:
window.onresize=function() { // 再执行一遍 center($('div'),$('body')) }
验证器工具https://c.runoob.com/front-end/61