CSS实现水平居中和垂直居中

1、水平居中

(1)

 .box {
            width: 200px;
            height: 200px;
            margin: 0 auto;
            background-color: aqua;
        }

(2)

  .box {
            position: absolute;
            left:50%;
            margin-left: -100px;
            width: 200px;
            height: 200px;
            background-color: aqua;
        }

(3)

 .box {
            position: absolute;
            left:50%;
            transform: -50%;
            width: 200px;
            height: 200px;
            background-color: aqua;
        }

(4)下面是写到父元素上,子元素居中,使用flex布局

   .box {
            display: flex;
            justify-content: center;
            width: 200px;
            height: 200px;
            background-color: aqua;
        }
        .son {
            width: 80px;
            height: 80px;
            background-color: blue;
        }

2、垂直居中

(1)

 .son {
            position: absolute;
            top: 0;
            bottom: 0;
            margin: auto 0 ;
            width: 80px;
            height: 80px;
            background-color: blue;
        }

(2)子元素被居中

.box {
            position: relative; 
            width: 200px;
            height: 200px;
            background-color: aqua;
            display:table-cell;
            vertical-align: middle;
        }
        .son {
            width: 80px;
            height: 80px;
            background-color: rgb(167, 167, 194);
        }

(3)

 .box {
            position: absolute;
            top: 50%;
            margin-top: -100px;
            width: 200px;
            height: 200px;
            background-color: chartreuse;
        }

(4)使用flex布局,父元素开启flex布局,子元素设置垂直居中

.box {     
            display: flex;
            width: 200px;
            height: 200px;
            background-color: aqua;
        }
        .son {
            align-self: center;
            width: 80px;
            height: 80px;
            background-color: blue;
        }

(5)

 .box {
            position: absolute;
            top: 50%;
            transform:  translateY(-50%);
            width: 200px;
            height: 200px;
            background-color: chartreuse;
        }

文本居中

水平居中 :text-algin:center;
垂直居中: line-hight:xxpx;(xx为父元素盒子的高度)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值