水平垂直居中代码示例8种(直接可用)

  1. flex
  2. grid
  3. table-cell
  4. margin + transform
  5. absolute + transform
  6. absolute + -margin
  7. absolute + margin:auto
  8. inline-block + vertical-align

案例展示:
在这里插入图片描述
代码:(直接可用)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* 方法1:flex */
        .wrap{
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* 方法2:grid写法1 */
        /* .wrap{
            display: grid;
        }
        .box{
            align-self: center;
            justify-self: center;
        } */
        /* 方法2:grid写法2 */
		/*.wrap {
            display: grid;
            align-items: center;
            justify-items: center;
        }*/
        /* 方法3:table-cell */
        /* 
        .wrap{
            display: table-cell;
            text-align: center;
            vertical-align:middle
        } 
        .box{
            display: inline-block;
        }
        */

        /* 方法4:margin + transform */
        /* .wrap{
            overflow:hidden
        }
        .box{
            margin: 50% auto;
            transform:translateY(-50%)
        } */

        /* 方法5:absolute + transform */
        /* .wrap{
            position: relative;
        }
        .box{
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
        }  */

        /* 方法6:absolute + -margin */
        /* .wrap{
            position: relative;
        }
        .box{
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -50px;
            margin-top: -50px;
        } */

        /* 方法7:absolute + margin:auto */
        /* .wrap{
            position: relative;
        }
        .box{
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
        } */
        
        /* 方法8:inline-block + vertical-align*/
        /* .wrap{
            text-align: center;
            line-height: 300px; 
        }
        .box{
            display: inline-block;
            vertical-align: middle;
        } */
    </style>
</head>

<body>
    <div class="wrap" style="width: 300px;height: 300px;background-color: yellow;">
        <div class="box" style="width: 100px;height: 100px;background-color: pink;">
        </div>
    </div>
</body>

</html>

代码学习来源视频:https://www.bilibili.com/video/BV1DK4y177EB/?spm_id_from=333.788.videocard.0

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值