弹性盒模型中flex-grow 和flex的区别

有没得发现这两功能一样的,不知道各位平时都习惯用哪个。首先,flex 属性是 flex-grow、flex-shrink 和flex-basis 属性的简写属性 ,通常我们认为flex-grow:1;与flex:1;是同一个意思,就是将子元素瓜分父容器的剩余空间1份。

那么你是不是有一个疑问,都能分配空间,那么到底有什么区别呢???

重点来了!!!!!这两个属性在放大时的计算方式不一样。

  1. flex-grow是对“父容器大小减去原本每个容器大小之和后的”的空间进行比例分配的。

比如下方例子,父容器宽600,子容器原本应该是每个100px,全部排列后剩余600-300=300,再对这300进行1:2的分配。所以一个分得100,一个分得200,加上原本的大小就是一个200,一个300。

  1. flex是对“父容器大小减去你没有flex的子容器的剩余全部大小”进行比例分配的。比如下方例子,父容器宽600,这里有一个没有flex的子元素,它的大小是100,那么剩余空间600-100=500,再对这500进行1:2的分配。所以一个分配100,一个分配200。

可以结合下面两个情况仔细区别。

1.flex-grow

<article>
        <div>flex-grow: 1;
            <p>200px</p>
        </div>
        <div>flex-grow: 2;
            <p>300px</p>
        </div>
        <div>3
            <p>100px</p>
        </div>
</article>
<style> 
article {
            width: 600px;
            height: 200px;
            margin: 50px auto;
            display: flex;
            border: 1px dashed black;
        }
        
        div {
            width: 100px;
            height: 100px;
        }
        
        div:nth-child(1) {
            flex-grow: 1;
            background-color: darkorange;
        }
        
        div:nth-child(2) {
            flex-grow: 2;
            background-color: skyblue;
        }
        
        div:nth-child(3) {
            background-color: thistle;
        }
</style>

结果图:

2.flex

<article>
        <div>flex-grow: 1;
            <p>166.66px</p>
        </div>
        <div>flex-grow: 2;
            <p>333.34px</p>
        </div>
        <div>3
            <p>100px</p>
        </div>
</article>
<style> 
article {
            width: 600px;
            height: 200px;
            margin: 50px auto;
            display: flex;
            border: 1px dashed black;
        }
        
        div {
            width: 100px;
            height: 100px;
        }
        
        div:nth-child(1) {
            flex: 1;
            background-color: darkorange;
        }
        
        div:nth-child(2) {
            flex: 2;
            background-color: skyblue;
        }
        
        div:nth-child(3) {
            background-color: thistle;
        }
</style>

效果图:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值