css 水平居中总结

 <div class="parent">
          <div class="child"></div>
          <span>我是span</span>
    </div>

1.行内块元素 display:inline-block元素,可以设置父元素 text-align:center

 .parent{
            background-color: aqua;
            text-align: center;
        }
        .child{
            width: 300px;
            height: 200px;
            background-color: blue;
        }
        span{
            display: inline-block;
        }

                       

2.定宽的元素水平居中(1)

     使用margin:0 auto 元素一定要有指定的宽度

     

 .child{
            width: 300px;
            height: 200px;
            background-color: blue;
            margin: 0 auto;
        }

                                      

 3.定宽的元素水平居中(2)

      对元素开启相对定位,使用left和margin-left

     

.child{
            width: 300px;
            height: 200px;
            background-color: blue;
            /* margin: 0 auto; */
            position: relative;
            left: 50%;
            /* 为元素宽度的一半 */
            margin-left: -150px;
        }

              效果与上图一样

 4.定宽的元素水平居中(3)

子元素开启绝对定位,父元素开启相对定位,使用left,right,margin(根据水平排列的那个等式)

 .parent{
            background-color: aqua;
            text-align: center;
            position: relative;
            height: 300px;
        }
            position: absolute;
            right: 0;
            left: 0;
            margin: auto;

 5.定宽的元素水平居中(4)

开启绝对定位和相对定位,使用left属性和transform属性

            position: absolute;
            left: 50%;
            transform: translateX(-50%);

 6.定宽的元素水平居中(5)

使用flex布局

 .parent{
            background-color: aqua;
            text-align: center;
            /* position: relative; */
            height: 300px;
            display: flex;
            justify-content: center;
            /* justify-content:space-between; */
        }

  7.定宽的元素水平居中(6)

使用Grid布局

 .parent{
            background-color: aqua;
            text-align: center;
            /* position: relative; */
            height: 300px;
            /* display: flex;
            justify-content: center; */
            /* justify-content:space-between; */

            display: grid;
            /* 方法一 */
            justify-items: center;
            /* 方法二 */
            justify-content: center;
 .child{
            width: 300px;
            height: 200px;
            background-color: blue;
            /* margin: 0 auto; */
            /* position: relative;
            left: 50%; */
            /* 为元素宽度的一半 */
            /* margin-left: -150px; */
            /* position: absolute;
            left: 50%;
            transform: translateX(-50%); */
            /* margin: auto; */
            /* 方法三 */
            margin: auto;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值