前端页面中子元素垂直居中的几种方式


1.使用flex

    这是最简单的一种方法,但是此种方法只兼容到IE10以上

<div class="parent">
  <div class="child">
    <div>
      我是child
    </div>
  </div>
</div>

.parent{
  display: flex;
  align-content: center;
  justify-content: center;
  background-color: #42b983;
  width: 400px;
  height:400px;
}

.child{
  width: 80%;
  height: 80%;
  background-color: #2c3e50;
}


2.使用line-height

    这种方法仅仅限于文本,当line-height设置为100时,整个子div充满父DIV

    

.parent{
  background-color: #42b983;
  wi100px;

  height:100px;dth: 
}

.child{
  line-height: 100px;
  background-color: yellow;
}


3.使用绝对定位+负margin

.parent{
  background-color: #42b983;
  width: 100px;
  height:100px;
  position: relative;
}

.child{
  position: absolute;
  left: 50%;
  top: 50%;
  width: 80px;
  height: 80px;
  margin-left: -40px;
  margin-top: -40px;
  background-color: yellow;
}

    

这种方法有个确定就是子元素的宽高值确定,不能适应自适应布局


4.使用绝对定位+margin

.parent{
  background-color: #42b983;
  width: 100px;
  height:100px;
  position: relative;
}

.child{
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  text-align: center;
  margin: auto 0;
  width: 80%;
  height: 80%;
  background-color: yellow;
}


5.使用transform实现居中

这种方法和第三种差不多,就是把负margin变成了transform,这种方法的优点是不用确定子元素的高度,缺点是兼容性不好

.parent{
  background-color: #42b983;
  width: 200px;
  height:200px;
  position: relative;
}

.child{
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%,-50%);
  -moz-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}

6.利用父,子元素的高和计算padding值

具体方法为 (父-子)/2 就是padding值,这个值就是父元素的padding


7.使用vertical-align:middle

.parent{
  background-color: #42b983;
  width: 200px;
  height:200px;
  /*position: relative;*/
  vertical-align: middle;
  display: table-cell;
}

.child{
  margin:  auto;
  width: 100px;
  height: 100px;
  background-color: yellow;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值