CSS盒子5种居中方式

1.使用margin进行固定长度的偏移

 #father{
         width: 100px;
         height: 100px;
         overflow:hidden;
         background-color: aqua;
        }
 #son{
         width: 50px;
         height: 50px;
         margin:0 auto;
         margin-top:25px;//这里的距离应该是子盒子的一半
         background-color: brown;
        }

2.使用绝对定位并进行偏移

       #father{
         width: 100px;
         height: 100px;
         background-color: aqua;
         position: relative;
        }
        #son{
         width: 50px;
         height: 50px;
         background-color: brown;
         position: absolute;
         left: 50%;
         margin-left: -25px;
         top:50%;
         margin-top: -25px;
         /* 使用计算公式:
         position: absolute;
         left:calc(50%,-25px);
         top:calc(50%,-25px); */
        }

3.使用绝对定位并margin自适应进行居中

        #father{
         width: 100px;
         height: 100px;
         background-color: aqua;
         position: relative;
        }
        #son{
         width: 50px;
         height: 50px;
         background-color: brown;
         position: absolute;
         left: 0;
         top:0;
         right: 0;
         bottom: 0;
         margin: auto;
        }

4.使用table-cell进行居中显示

        #father{
         width: 100px;
         height: 100px;
         background-color: aqua;
         display: table-cell;
         vertical-align: middle;
        }
        #son{
         width: 50px;
         height: 50px;
         background-color: brown;
         margin: 0 auto;
        }
/*这段CSS代码的作用是将一个元素以表格单元格(table-cell)的形式呈现,并设置其
垂直对齐方式为居中(vertical-align: middle)。

`display: table-cell;` 的作用是将元素以表格单元格的形式呈现。表格单元格会自动
进行水平和垂直居中,类似于HTML表格中的单元格。使用这种布局方式可以方便地实现垂
直居中的效果。

`vertical-align: middle;` 的作用是设置元素的垂直对齐方式为居中。这会使元素相对
于其父容器的中心垂直居中,无论元素的高度是多少。

综合起来,这段代码的效果是将元素以表格单元格的形式呈现,并使其垂直方向上相对于
父容器居中对齐。这种技术常用于制作垂直居中的布局,特别适用于一些需要在未知高度的
容器中实现垂直居中的内容,比如垂直居中文本、图像等。*/

5.使用弹性盒子来实现居中

        #father{
         width: 100px;
         height: 100px;
         background-color: aqua;
         display: flex; 
         justify-content: center; 
         align-items: center; 
        }
        #son{
         width: 50px;
         height: 50px;
         background-color: brown;
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值