如何让子元素在父元素的中间?

方法一:用定位

 <style>
        .son1_green{
            width: 200px;
            height: 200px;
            background-color: green;
            position: absolute;
            left:0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
        }
        
        .fa1_red{
            background-color: red;
            height: 400px;
            width: 400px;
            position: relative;
        }
    </style>
    <div class="fa1_red">
        <div class="son1_green"></div>
    </div>

显示效果如下图所示

康哥说:只有绝对定位的元素才可以,意思就是绝对定位之后如果设置了 margin: auto,

那么 margin-top 和 margin-right 不再为0,而是 auto,

同时需要设置 top,bottom,left,right为0 来找到父元素的位置,

然后 margin: auto 会找到父元素的位置分配好上下左右外边距,从而实现水平垂直居中!

方法二:怪异盒子

<style>
        .son1_green{
            width: 200px;
            height: 200px;
            background-color: green;
          
        }
        
        .fa1_red{
            background-color: red;
            height: 400px;
            width: 400px;
            padding:100px;
            box-sizing: border-box;
        }
    </style>
    <div class="fa1_red">
        <div class="son1_green"></div>
    </div>

效果同上

原理就是用padding压缩父盒子的内容显示区,并设置怪异盒子使不会改变父盒子的宽高。

方法三:弹性布局

<style>
        .v1{
            width: 500px;
            height: 500px;
            background-color: aquamarine;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .v2{
            width: 200px;
            height: 200px;
            background-color: pink;

        }
    </style>
    <div class="v1">
        <div class="v2"></div>
    </div>

效果如下

原理开启浮动布局,并对浮动子元素进行,主轴侧轴方向的排列。

方法四:用浮动+margin

 <style>
        .v1{
            width: 500px;
            height: 500px;
            background-color: aquamarine;
            
        }
        .v2{
            width: 200px;
            height: 200px;
            background-color: pink;
            /* float: left; */
            float: left;
            margin-left: calc((500px - 200px)/2);
            margin-top: calc((500px - 200px)/2);
            
        }
    </style>
    <div class="v1">
        <div class="v2"></div>
    </div>

效果如下

利用浮动避免父元素与子元素一起移动

方法五:只用margin(padding)

<style>
        .v1{
            width: 500px;
            height: 500px;
            background-color: aquamarine;
            
        }
        .v2{
            width: 200px;
            height: 200px;
            background-color: pink;
            float: left;
            margin-left: calc((500px - 200px)/2);
            margin-top: calc((500px - 200px)/2);
            
        }
    </style>
    <div class="v1">
        <div class="v2"></div>
    </div>

用margin放到中间

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值