JS實現在不知道盒子寬高的情況下,預設讓盒子在頁面中水平垂直居中
阿新 • • 發佈:2019-01-24
當然在我們知道寬高的情況下,
1、我們通過CSS的中的絕對定位實現
#box{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
2、通過CSS中的margin=auto,四個方向都為0的方法也可以實現
#box{
width:200px;
height:200px;
margin:auto;
position:absolute;
top:0;
right :0;
bottom:0;
left:0;
}
3、可以通過CSS3的彈性佈局(flex),實現盒子的居中
廢話不多說,直接上程式碼.
body {
display: flex;
align-items: center; /*定義body的元素垂直居中*/
justify-content: center; /*定義body的裡的元素水平居中*/
}
#box{
height:200px;
width:200px;
background-color:red;
}
不知道寬高的情況下
我們可以通過JS中先獲取一屏的寬高,再獲取到盒子的寬高
var windH = document.documentElement.clientHeight||document.body.clientHeight; //獲取一屏的高度。(兩種寫法為了相容所有瀏覽器)
var windW = document.documentElement.clientWidth||document.body.clientWidth; //獲取一屏的寬度。
var boxH = document.getElementById('box').offsetHeight; //獲取盒子的高度(border(top\bottom)+padding(top\bottom)+height)
var boxW = document.getElementById('box').offsetWidth; //獲取盒子的寬度(border(left\right)+padding(left\right)+width)
#box.style.top=(winH-boxH)/2+'px';
#box.style.left=(winW-boxW)/2+'px';
以上幾種方式都可以使得盒子水平垂直居中。。。