几种常见的水平垂直居中实现方式

一、利用绝对定位

<div class="box">
  <div class="child">水平垂直居中</div>
</div>
 
<style>
.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  position: relative;
}
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: red;
}  
</style>

二、利用flex布局设置居中 

<div class="box">
  <div class="child">水平垂直居中</div>
</div>
 
<style>
.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  display: flex;
  align-items: center; // 纵轴对齐方式,默认是纵轴 子元素垂直居中
  justify-content: center; //纵轴对齐方式,默认是纵轴
}
.child {
  background: red;
}  
</style>

三、flex给子项设置 

<div class="box">
  <div class="child">水平垂直居中</div>
</div>
 
<style>
.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  display: flex;
}
.child {
  background: red;
  margin: auto; // 水平垂直居中
}  
</style>

四、给容器加给伪元素 

<div class="box">
  <div class="child">水平垂直居中</div>
</div>
 
<style>
.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  text-align: center;
}
.box::after {
  content: "";
  line-height: 200px;
}
.child {
  display: inline-block;
  background: red;
}
  
</style>

五、tabel-cell实现垂直居中 

<div class="box">
  <div class="child">水平垂直居中</div>
</div>
 
<style>
.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  display: table-cell;
  vertical-align: middle;  // 设置元素在垂直方向上的对齐方式
  text-align: center;
}
.child {
  background: red;
  display: inline-block;
}  
</style>

六、利用grid设置居中

 <div class="box">
  <div class="child">水平垂直居中</div>
</div>
 
<style>
.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  display: grid;
  align-items: center;
  justify-content: center;
}
.child {
  background: red;
}  
</style>

七、grid给子项设置 

<div class="box">
 <div class="child">水平垂直居中</div>
</div>
 
<style>
.box {
 width: 200px;
 height: 200px;
 border: 1px solid;
 display: grid;
}
.child {
 background: red;
 margin: auto;
}  
</style> 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值