flex-growflex-shrinkflex-basis

tech2023-12-30  68

1.flex-grow

该属性定义弹性盒子的拉伸因子,默认值为0,即表示不拉伸

来看一个简单的例子,总宽度为500px的container下面有3个item,他们的宽度均设置为100px,flex-grow分别设置为1, 2, 3,如果忽略flex-grow的话,container会有200px的剩余空间,加上flex-grow之后,这200px会按照1:2:3的比例分配剩余空间,也就是a将分得33.33px的剩余空间,b将分得66.66px的剩余空间,c将分得100px的剩余空间

<style> body { margin: 0; } .container { display: flex; height: 300px; width: 500px; } .item { height: 100%; } .a { width: 100px; flex-grow: 1; background: #cccccc; } .b { width: 100px; flex-grow: 2; background: bisque; } .c { width: 100px; flex-grow: 3; background: palegoldenrod; } </style> <body> <div class="container"> <div class="item a"></div> <div class="item b"></div> <div class="item c"></div> </div> </body>

2.flex-shrink

该属性表示了flex元素的压缩规则,默认值是1,即表示在默认情况下不压缩

再来看一个简单的例子,500px的container下面有3个宽度均为200px的item,现在给它们的flex-shrink分别设置为1, 2, 3,由于flex是默认不换行的,那么这3个item肯定会被压缩压缩比例为1:2:3,即a会被压缩100/6px, b会被压缩100*2/6px, c会被压缩100*3/6px

<style> body { margin: 0; } .container { display: flex; height: 300px; width: 500px; } .item { height: 100%; } .a { width: 200px; background: #cccccc; flex-shrink: 1; } .b { width: 200px; background: bisque; flex-shrink: 2; } .c { width: 200px; background: palegoldenrod; flex-shrink: 3; } </style> <div class="container"> <div class="item a"></div> <div class="item b"></div> <div class="item c"></div> </div>

3. flex-basis

该属性指定了flex元素主轴方向的初始大小,默认值是auto

<style> body { margin: 0; } .container { display: flex; height: 300px; width: 500px; } .item { height: 100%; width: 100px; } .a { background: #cccccc; flex-basis: 200px; } .b { max-width: 50px; flex-basis: 100px; background: bisque; } .c { background: palegoldenrod; } </style> <div class="container"> <div class="item a"></div> <div class="item b"></div> <div class="item c"></div> </div>

flex-basic计算的优先级

max-width/min-width > flex-basis > width > box
最新回复(0)