CSS实现水平居中以及垂直居中的方法

水平居中

  • 行内元素: text-align: center
  • 块级元素: margin: 0 auto
  • position:absolute+left:50%+ transform:translateX(-50%)
  • display:flex + justify-content: center

垂直居中

  • 设置line-height 等于height
  • position:absolute +top:50%+transform:translateY(-50%)
  • display:flex + align-items: center
  • display:table+display:table-cell + vertical-align: middle;

如下代码所示:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .main{
      height: 100vh;
      width: 100vw;
      font-size: 20px;
      color: #fff;
    }
    .demo1{
      text-align: center;
      width: 400px;
      height: 200px;
      background-color: #526232;
    }
    .demo2{
      text-align: center;
      width: 400px;
      height: 200px;
      background-color: #27ce43;
    }
    .demo3{
      display: flex;
      justify-content: center;
      width: 400px;
      height: 200px;
      background-color: #526232;
    }
    .demo4{
      text-align: center;
      width: 400px;
      height: 200px;
      background-color: #27ce43;
      position: relative;
    }
    .text{
      height: 100%;
      width: 100%;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
    .demo5{
      height: 200px;
      width: 400px;
      line-height: 200px;
      background-color: #526232;
    }
    .demo6{
      display: flex;
      align-items: center;
      width: 400px;
      height: 200px;
      background-color: #27ce43;
    }
    .demo7{
      position: relative;
      height: 200px;
      width: 400px;
      background-color: #526232;
    }
    .text1{
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    .demo8{
      display: table;
      width: 400px;
      height: 200px;
      background-color: #27ce43;
    }
    .text3{
      display: table-cell;
      vertical-align: middle;
    }
  </style>
</head>
<body>
  <div class="main">
    <div class="demo1">水平居中: text-aligen:ceter</div>
    <div class="demo2">水平居中: margin:0 auto</div>
    <div class="demo3">水平居中:flex justify-content: center </div>
    <div class="demo4">
      <div class="text">水平居中:position absolute left transform </div>
    </div>
  </div>
  <div class="main">
    <div class="demo5">垂直居中:height=liner-height</div>
    <div class="demo6">垂直居中:flex align-item:center</div>
    <div class="demo7">
      <div class="text1">垂直居中:position absolute top transfrom</div>
    </div>
    <div class="demo8">
      <div class="text3">垂直居中:表格布局</div>
    </div>
  </div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值