元素水平垂直居中的几种方式

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>元素水平、垂直居中</title>
  <style>
    body {
      margin: 0px 0px;
      padding: 20px 20px;
    }

    /* 公共css */
    .demo {
      width: 300px;
      height: 300px;
      border: 1px solid black;
      position: relative;
    }

    .box {
      position: absolute;
      width: 200px;
      height: 200px;
      background-color: red;
    }

    /* demo1 */
    .box1 {
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }

    /* demo2 */
    .box2 {
      left: calc(50% - 100px);
      top: calc(50% - 100px);
    }

    /* demo3 */
    .demo3 {
      width: 300px;
      height: 300px;
      border: 1px solid black;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    /* demo4 */
    .box4 {
      left: 50%;
      top: 50%;
      margin-left: -100px;
      margin-top: -100px;
    }

    /* demo5 */
    .demo5 {
      width: 300px;
      height: 300px;
      border: 1px solid black;
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }

    .box5 {
      width: 200px;
      height: 200px;
      background-color: red;
      display: inline-block;
    }
  </style>
</head>

<body>
  <div class="demo">
    <div class="box box1">demo1</div>
  </div>
  <div class="demo">
    <div class="box box2">demo2</div>
  </div>
  <div class="demo3">
    <div class="box box3">demo3</div>
  </div>
  <div class="demo">
    <div class="box box4">demo4</div>
  </div>
  <div class="demo5">
    <div class="box5">demo5</div>
  </div>
  <script></script>
</body>

</html>

实现效果:

在这里插入图片描述
在这里插入图片描述
参考文档请点击这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值