3种用于使div居中的方法总结
<!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;
}
</style>
</head>
<body>
<div id="div1">
<button id="btn"></button>
</div>
<script>
window.onload=function(){
//利用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>
</html>
但三种方式,利用CSS3的flex,通过设置父元素display:flex;子元素设置为margin:atuo
<!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-item {
background-color: cornflowerblue;
width: 75px;
height: 75px;
margin: 10px;
}
.flex-item{
margin: auto;
}
</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>