1、前兩種方法都是通過css樣式來做到的,第三種是通過JS實現的
第一種方法:IE8以下 不兼容
div {
width: 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 width: 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;
}