div水平垂直居中的方法
*方法1:使用JS實現:兼容全部的瀏覽器
<script type="text/javascript">
//->獲取當前屏幕的寬度和高度
var winW = document.documentElement.clientWidth || document.body.clientWidth,
winH = document.documentElement.clientHeight || document.body.clientHeight;
//->獲取盒子的寬度和高度
var box = document.getElementById("box"),
boxW = box.offsetWidth,
boxH = box.offsetHeight;
box.style.position = "absolute";
box.style.left = (winW - boxW) / 2 + "px";
box.style.top = (winH - boxH) / 2 + "px";
</script>
- 方法2 :使用CSS實現:兼容全部的瀏覽器
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.box {
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px; /*--上邊距等於負的高度的一半值--*/
margin-left: -100px; /*--左邊距等於負的寬度的一半值--*/
width: 200px;
height: 200px;
border: 2px solid green;
}
</style>
上述的這種方式需要知道具體的寬度和高度,並計算出具體的margin值纔可以實現,如果後期寬高值修改,我們的margin的值也需要修改
*方法3:使用CSS實現:不兼容IE6~7(目前移動端項目的居中採用這種方法即可)
.box {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 200px;
height: 200px;
border: 2px solid green;
}