<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定位到window中心</title>
<script src="../../js/jquery.min.js"></script>
<script src="../../js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../../js/easyui-lang-zh_CN.js"></script>
<style type="text/css">
#div1 {
width: 400px;
height: 400px;
border: 1px blue solid;
position: absolute
}
//利用css樣式居中
#btn {
margin: -150px 0 0 -150px;
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 300px;
}javascript
</style>
</head>css
<body>
<div id="div1">
<button id="btn"></button>
</div>
<script>
window.onload=function(){html
//利用client和offset居中
function center(obj){
var offsetHeight=document.documentElement.clientHeight||document.body.clientHeight;
var offsetWidth=document.documentElement.clientWidth||document.body.clientWidth;
var scrollTop=document.documentElement.offsetTop||document.body.offsetTop;
var scrollLeft=document.documentElement.offsetLeft||document.body.offsetLeft;
alert(offsetHeight);
obj.style.top=(offsetHeight- obj.offsetHeight) / 2 + scrollTop + "px";
obj.style.left=(offsetWidth - obj.offsetWidth) / 2 + scrollLeft + "px";
}
var oDiv=document.getElementById("div1");
center(oDiv);
}
</script>
</body>java
</html>jquery
但三種方式,利用CSS3的flex,經過設置父元素display:flex;子元素設置爲margin:atuoweb
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<style>
.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}flex
.flex-item {
background-color: cornflowerblue;
width: 75px;
height: 75px;
margin: 10px;
}ui
.flex-item{
margin: auto;
}htm
</style>
</head>
<body>教程
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
<div class="flex-item">flex item 3</div>
</div>
</body>
</html>
第四種方式,利用CSS3的flex,經過設置父元素display:flex;
justify-content: center;/*X軸方向居中*/
align-items: center;/*Y軸方向居中*/來達到居中的效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<style>
.flex-container {
display: -webkit-flex;/*指出div彈性盒子模型*/
display: flex;
-webkit-justify-content: center;
justify-content: center;/*X軸方向居中*/
align-items: center;/*Y軸方向居中*/
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
<div class="flex-item">flex item 3</div>
</div>
</body></html>