css水平垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>垂直居中</title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }
        body {
            background: red;
        }
       /*
       第一种:
            利用calc计算

        .box {
            width: 900px;
            height: 900px;
            line-height: 900px;
            text-align: center;
            background: red;
            position: absolute;
            top: calc(50% - 300px);
            left: calc(50% - 300px);
        }
         */
        /*
           第二种:
           在ie9及以下不起作用
            transform

        .box {
            width: 800px;
            height: 800px;
            line-height: 800px;
            text-align: center;
            background: orange;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
 */
        /*
            第三种:
                使用视口单位vw和vh
                1vw、1vh是与视口相关
                1vw是与视口,1vw = 视口宽度的1%
                1vh = 视口高度的1%

        .box {
            text-align: center;
            background: yellow;
            width: 700px;
            height: 700px;
            line-height: 700px;
            padding: 1em 1.5em;
            margin: 50vh auto 0;
            transform: translateY(-50%);
        }
 */
        /*
            第四种:
            flex的解决方案

        body {
            display: flex;
            min-height: 100vh;
            margin: 0;
        }
        .box {
            width: 600px;
            height: 600px;
            background: green;
            line-height: 600px;
            text-align: center;
            margin: auto;
        }
*/
        /*
        第五种:
            万能居中
            使用margin和绝对定位
            */
         .box {
            width: 500px;
            height: 500px;
            line-height: 500px;
            text-align: center;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            background: purple;
        }

    </style>
</head>
<body>
<div class="box">
    水平垂直居中
</div>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啊哈前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值