CSS垂直居中的方法

CSS在实际开发中或者在面试的时候,都是一个绕不开的话题。而关于css经典问题“垂直居中”更是经常霸榜的存在。往往最容易的可能最容易忽略,本次分享多钟垂直居中的方案。

垂直居中分为俩种,一种是元素宽、高已知;一种是元素宽、高未知

一、宽高已知

1、absolute + margin auto

利用当前元素的 position: absolute; 和 margin: auto将当前元素的绝对定位值都设置为 0,将 margin 设置为 auto,就可以实现元素的垂直居中。

.divBox{
  position: relative;
  width: 100px;
  height: 100px;
}


.item{
  width: 50px; 
  height: 50px;
  position:absolute;
  top: 0; bottom: 0; left: 0; right: 0;
  margin: auto;
}

2、absolute + 负 margin

当前元素元素相对父元素绝对定位 50% ,然后再使用margin-left和margin-top负值来调整位置,达到实现效果

.divBox{
  position: relative;
  width: 100px;
  height: 100px;
}


.item{
  width: 50px; 
  height: 50px;
  position:absolute;
  top: 50%; left: 50%;
  margin-left: -25px;
  margin-top: -25px;
}

3、absolute + calc

calc是css3的新增特性,用来计算相关数值。

.divBox{
  position: relative;
  width: 100px;
  height: 100px;
}


.item{
  width: 50px; 
  height: 50px;
  position:absolute;
  top: 50%; left: 50%;
  margin-left: calc(50% - 25px);
  margin-top: calc(50% - 25px);
}

二、元素宽高未知

1、absolute + transform

 利用css3的新特性 transform,来移动定位元素。

.divBox{
  position: relative;
  width: 100px;
  height: 100px;
}


.item{
  width: 50px; 
  height: 50px;
  position:absolute;
  top: 50%; left: 50%;
  transform: translate(50%, 50%);
}

2、line-height + vertical-align

设置当前元素为行内元素,设置父元素的 text-align: center; 实现水平居中

设置当前元素的 vertical-align: middle; 来实现垂直居中;

最后设置当前元素的 line-height: initial; 来继承父元素的line-height

.divBox{
  width: 100px;
  line-height: 100px;
  text-align: center;
}

.item{
  display: inline-block;
  vertical-align: middle;
  line-height: initial;
}

3、table 表格元素

<table>
  <tbody>
    <tr>
      <td class="divBox">
        <div class="item"></div>
      </td>
    </tr>
  </tbody>
</table>

<style>
.divBox{
  width: 100px;
  height: 100px;
  text-align: center;
}
.item{
   display: inline-block;
}

4、flex 布局

justify-content设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式

align-items定义 flex 子项在 flex 容器的当前行的侧轴(纵轴)方向上的对齐方式

.divBox{
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.item{
  background: orange;
}

5、flex + margin auto

.divBox{
  width: 100px;
  height: 100px;
  display: flex;
}
.item{
 margin: auto;
}

还有一种是display:grid的布局方式,但是没有在项目中使用过,这里不在过多的叙述。感兴趣的可以阅读下此篇文章,链接附上CSS3中的display:grid,网格布局介绍_CSS教程-考高分网

本次分享完成~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值