如何使子盒子在父盒子里面水平垂直居中?

在css的应用中,让子盒子在父盒子里面水平垂直居中我们有三种方法:

首先我们需要先创建两个盒子,再给盒子添加css属性;

第一种:

.box1 {

            /* 相对定位 */

            position: relative;

            width: 600px;

            height: 600px;

            background-color: pink;

        }

       

        .box2 {

            /* 绝对定位 */

            position: absolute;

            /* 第一步: 先将子盒子向上及向左移动父盒子的50%;*/

            top: 50%;

            left: 50%;

            /* 第二步:再让子盒子移动自身宽高的一般半*/

            margin-top: -100px;

            margin-left: -100px;

            width: 200px;

            height: 200px;

            background-color: blue;

        }

第二种:

   .box1 {

            /* 相对定位 */

            position: relative;

            width: 600px;

            height: 600px;

            background-color: pink;

        }

       

        .box2 {

            /* 绝对定位 */

            position: absolute;

            /* 将子盒子的上右下左四个属性都设置为0 */

            top: 0;

            right: 0;

            bottom: 0;

            left: 0;

            /* 再将盒子外边距设置为auto */

            margin: auto;

            width: 200px;

            height: 200px;

            background-color: blue;

        }

第三种:

.box1 {

            /* 相对定位 */

            position: relative;

            width: 600px;

            height: 600px;

            background-color: pink;

        }

       

        .box2 {

            /* 绝对定位 */

            position: absolute;

            /* 第一步: 先将子盒子向上及向左移动父盒子的50%; */

            top: 50%;

            left: 50%;

            /*第二步: 使用 transform位移 值为百分比时:参照自身宽高;

            值为px时:参照父盒子宽高移动 */

            transform: translate(-50%, -50%);

            width: 200px;

            height: 200px;

            background-color: blue;

        }

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值