元素垂直居中的方式

目录

1.定位 + margin

2.定位 + transform

3.flex 布局

4.grid 网格布局

5.table 表格元素


1.定位 + margin

.parent{
  position: relative;
  width: 90px;
  height: 90px;
  border: 3px solid red;
}
 
.child{
  background: #000000;
  width: 50px;
  height: 50px;
  position:absolute;
  top: 0; bottom: 0; left: 0; right: 0;
  margin: auto;
}

2.定位 + transform

.parent{
  width: 90px;
  height: 90px;
  border: 3px solid red;
  position:relative;
}
 
.child{
  background: #000000;
  position:absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

3.flex 布局

.parent {
  width: 90px;
  height: 90px;
  border: 3px solid red;
  display: flex;
  justify-content: center;
  align-items: center;
}
.child{
  background: #000000;
}

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

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

4.grid 网格布局

.parent{
  width: 90px;
  height: 90px;
  border: 3px solid red;
  display: grid;
  align-items: center;
  justify-content: center;
}
 
.child{
  background: #000000;  
}

5.table 表格元素

.parent{
  width: 90px;
  height: 90px;
  border: 3px solid red;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
 
.child{
  background: #000000;
  //设为块级元素
  display: inline-block;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值