flex的三个属性

flex:flex-grow flex-shrink flex-basis

  • flex-grow:定义放大比例,默认为0,规定项目相对于其他灵活的项目进行扩展的量
  • flex-shrink: 定义了项目的缩小比例,仅在宽度之和大于容器的时候才会发生收缩,其收缩的大小是依据 flex-shrink 的值,默认为1
  • flex-basis:给上面两个属性分配多余空间之前, 计算项目是否有多余空间, 默认值为 auto, 即项目本身的大小

说起来听拗口也不怎么好理解,直接上代码吧!

示例1:

子元素都设置为flex:1的时候平均分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,
        body {
            padding: 0;
            margin: 0;
        }

        .parent {
            width: 1000px;
            display: flex;
            border: 1px solid #000;
            margin: 50px;
        }

        .parent div {
            height: 200px;
            flex: 1;
        }

        .child-1 {
            background-color: #888;
        }

        .child-2 {
            background-color: #f55;
        }

        .child-3 {
            background-color: #55f;
        }
    </style>
</head>

<body>

    <div class="parent">
        <div class="child-1"></div>
        <div class="child-2"></div>
        <div class="child-3"></div>
    </div>

</body>

</html>

flex:1 ===  flex-grow: 1; flex-shrink: 1; flex-basis: 0%;

 

实现固定1:3:2比例排列:

将子元素的flex分别设置为1,3,2,即可实现1:3:2的布局排列

.child-1 {
    flex: 1;
    background-color: #888;
}

.child-2 {
    flex: 3;
    background-color: #f55;
}

.child-3 {
    flex: 2;
    background-color: #55f;
}

示例2:

flex-basis:

.child-1 {
    flex-grow: 1;
    flex-basis: 400px;
    background-color: #888;
}

将第一个子元素flex-basis设置为400px,则容器剩余分配部分为1000px-400px=600px,

child-1: 400+600*(1/(1+3+2))=500px

child-2: 600*(3/(1+3+2))=300px

child-3: 600*(2/(1+3+2))=200px

 

示例3:

flex-shrink:

.parent div {
    height: 200px;
    flex-grow: 1;
    flex-basis: 400px;
}

.child-1 {
    flex-shrink: 1;
    background-color: #888;
}

.child-2 {
    flex-shrink: 2;
    background-color: #f55;
}

.child-3 {
    flex-shrink: 7;
    background-color: #55f;
}

这里将三个子元素的flex-grow都设为1,flex-basis都设置为400px,在不设置flex-shrink的情况下即使3*400=1200px大于容器的1000px,但是依旧会平均分。

这里将子元素的flex-shrink分别设置为1,2,7,则:超出部分为400*3-1000=200px

child-1: 400px-200px*(1/(1+2+7))=380px

child-2: 400px-200px*(2/(1+2+7))=360px

child-3: 400px-200px*(7/(1+2+7))=260px

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值