盒子在页面居中的三种方法

1、前两种方法都是通过css样式来做到的,第三种是通过JS实现的

  第一种方法:IE8以下 不兼容

   

div {
             100px;
            height: 100px;
            background: red;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }

  第二种方法:兼容IE11,10、9、8、7、5(亲测)

   左右都为50%的边距,最后要减去自身的宽高的一半,所以margin-left 和 margin-top为负数

 1 div {
 2              100px;
 3             height: 100px;
 4             background: red;
 5             position: absolute;
 6             top: 50%;
 7             left: 50%;
 8             margin-top: -50px;
 9             margin-left: -50px;
10     }

  第三种方法

  var$div = document.querySelector('div');

function Center(ev) {
ev = ev || window.event;
//获取盒子宽度
var $div_width = $div.offsetWidth;
//获取盒子高度
var $div_height = $div.offsetHeight;
//获取window 高度
var Height = window.innerHeight;
//获取window 宽度
var Width = window.innerWidth;
console.log(Width);
//计算盒子距离顶部的距离
var top = (Height - $div_height)/2
//计算盒子距离左边的距离
var left = (Width - $div_width) / 2

$div.style.top = top + 'px';
$div.style.left = left + 'px';
console.log(Height);
}
Center();
div {
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
原文地址:https://www.cnblogs.com/TreeCTJ/p/9686255.html