首页 > Web开发 > 详细

JS 实现 HTML div || 标签 居中

时间:2020-02-12 16:47:08      阅读:68      评论:0      收藏:0      [点我收藏+]
  • 拿来即食
<!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‘))
}

 

JS 实现 HTML div || 标签 居中

原文:https://www.cnblogs.com/tacty/p/12299574.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!