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.οnlοad=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>

转载于:https://www.cnblogs.com/tangjie-93/p/7697918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值