DIV+CSS实现盒子居中的几种方法比较(考虑兼容性)

例子中html代码如下:

<div class="center"></div>

为了让结果更清晰加上如下的css样式

.center{
  width:100px;
  height: 100px;
  background-color: gray;
}

1. 实现水平居中

1) margin: 0 auto——IE6-8,chrome和mozilla测试有效

这是常用的方法,该方法兼容IE6-8,chrome和mozilla


2) 父元素设置text-align: center——但是该方法只适用于IE6,IE7

例如设置:

body{
  text-align: cenert;
}


3) 利用position:absolute和margin——IE6-8,chrome和mozilla测试有效

.center{
  position: absolute;
  left: 50%;
  margin-left: -50%;
}
这里用left:50%使div的左边界距离窗口50%,但是需要向左移动50%的width(div本身的宽度)才能真正实现水平居中;

也可以替换left和margin-left:

.center{
  position: absolute;
  margin-left: 50%;
  left: -50px;
}

2. 实现水平垂直居中

1) 利用position: absolute和margin:auto——兼容IE8,chrome和mozilla,但是不兼容IE6-7

.center{
  position: absolute;
  top:0;
  bottom:0;
  left:0;  
  right:0;
  margin: auto;
}
可能有人认为利用margin: 0 auto可以实现水平居中, 那么margin: auto 0和margin: auto可以分别实现垂直居中和水平垂直居中,但是其实是错误的。前者无法实现居中,而后者也只能实现水平居中。但是配合position: absolute就能实现水平垂直居中。 


2) 利用position: absolute和margin——IE6-8,chrome和mozilla测试有效

.center{
  position: absolute;
  left: 50%;
  margin-left: -50px;
  left: 50%;
  margin-left: -50px;
}


3)利用css3中的flex弹性盒子——不支持IE

<div class="container">
  <div class="center"></div>
</div>
css:

.container{
  width:500px;
  height:500px;
  background:yellow;
  display: flex;
}
.center{
  width:100px;
  height:100px;
  background:gray;
  margin:auto
}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值