css中实现元素居中的方式

1、文字以及行内元素居中

水平居中: text-align: center;

垂直居中:line-height: 行高;

        .box{
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            text-align: center;
            line-height: 200px;
        
        }

 2、块级元素的居中方式

1、利用弹性布局居中元素

给父元素设置弹性布局,在设置水平居中,垂直居中

        .box{
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: pink;
        }

 

2、使用定位以及负外边距来设置居中

给父元素设置相对定位,子元素设置绝对定位,再给子盒子设置top  left都为50% ,margin-left: -50px;margin-top: -50px;

        .box{
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            position: relative;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: rgb(241, 120, 140);
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }

 

3、利用定位加css位移 

给父元素设置相对定位,子元素设置绝对定位,再给子盒子设置top  left都为50%,再给子元素设置transform:translate(-50%,-50%)

4、使用弹性布局加margin:auto

 父元素设置display:flex,子元素 margin: auto

 

        .box{
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            display: flex;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: rgb(226, 128, 8);
            margin: auto;
        }

 

 5、使用grid网格布局

 给父元素设置弹性布局,display: grid;justify-content: center;align-items: center;

 

         .box{
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            display: grid;
            justify-content: center;
            align-items: center;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: rgb(75, 26, 223);
            
        }
 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值