DIV的常用的几种绝对居中方法

本文介绍了四种常见的用于使DIV元素在页面上绝对居中的方法:一是利用margin和绝对定位,二是同样方法但通过百分比计算,三是借助flex布局,四是CSS3 transform。针对不同情况,如元素宽高固定或不固定,提供了适用的解决方案。
摘要由CSDN通过智能技术生成

DIV的常用的几种绝对居中方法

方法一:利用margin和绝对定位一

优点:

1.支持跨浏览器,包括IE8-IE10

缺点:

1.必须声明宽高度。

<div class="container">
	<div class="box"></div>
</div>
.container {
  position: relative;
  width: 200px;
  height: 200px;
  background-color: pink;
}
.container .box {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 100px;
  height: 100px;
  background-color: skyblue;
}

方法二:利用margin和绝对定位二

优点:

1.支持跨浏览器,包括IE8-IE10

缺点:

1.必须声明宽高度。

<div class="container">
	<div class="box"></div>
</div>
.container {
  position: relative;
  width: 200px;
  height: 200px;
  background-color: pink;
}
.container .box {
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -50px;
  width: 100px;
  height: 100px;
  background-color: skyblue;
}

方法三:利用flex弹性布局

优点:

1.弹性布局,对宽高无既定要求

缺点:

1.有兼容性问题(IE11+才支持)。

<div class="container">
	<div class="box"></div>
</div>
.container {
  display: flex;
  justify-content: center; /*水平居中*/
  align-items: center; /*垂直居中*/
  width: 200px;
  height: 200px;
  background-color: pink;
}
.container .box {
  width: 100px;
  height: 100px;
  background-color: skyblue;
}

方法四:利用CSS3新特性transform

优点:

1.弹性布局,对宽高无既定要求

<div class="container">
	<div class="box"></div>
</div>
.container {
  position: relative;
  width: 200px;
  height: 200px;
  background-color: pink;
}
.container .box {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  background-color: skyblue;
  transform: translate(-50%, -50%);
}

缺点:

1.有兼容性问题(IE10+才支持)。

总结:

对于宽高固定的元素:

1.使用第一、第二种方法

对于宽高不固定的元素:

1.使用第三、第四种方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值