CSS 5种垂直水平居中的实现方法(包括table和grid布局)

首先需要创建一个容器,容器种添加一个小div,实现小div在容器种的垂直水平居中。

<style>
    * {
      margin: 0;
      padding: 0;
    }
    .container {
      width: 500px;
      height: 500px;
      background-color: orange;
      margin: 0 auto;
    }
    .content {
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="content"></div>
  </div>
</body>

1.方法一:在已知宽度的情况下,对div改变外边距进行偏移达到效果
代码:


    .container {
      width: 500px;
      height: 500px;
      background-color: orange;
      position: relative;
      margin: 0 auto;
    }
    .content {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 50%;
      left: 50%;
      margin: -50px 0 0 -50px;
    }

2.方法二:宽度可未知的情况,使用tansform属性达到效果


    .container {
      width: 500px;
      height: 500px;
      background-color: orange;
      position: relative;
      margin: 0 auto;
    }
    .content {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

3.方法三:使用弹性布局flex

    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 500px;
      height: 500px;
      background-color: orange;
      margin: 0 auto;
    }
    .content {
      width: 100px;
      height: 100px;
      background-color: red;
    }

4.方法四:使用table-cell,需要注意的是content块需要给予inline-block


    .container {
      display: table-cell;
      /* 垂直居中 */
      vertical-align: middle;
      /* 水平居中 */
      text-align: center;
      width: 500px;
      height: 500px;
      background-color: orange;
    }
    .content {
      display: inline-block;
      width: 100px;
      height: 100px;
      background-color: red;
    }

5.方法五:使用grid布局


    .container {
      display: grid;
      width: 500px;
      height: 500px;
      background-color: orange;
      margin: 0 auto;
    }
    .content {
      width: 100px;
      height: 100px;
      background-color: red;
      justify-self: center;
      align-self: center;
    }

如有其他方法,后期补充。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值