Flexbox - 灵活性


弹性基础

我们使用flex-basis属性来定义弹性项目在分配空间之前的默认大小。

以下示例演示了 flex-basis 属性的用法。在这里,我们创建 3 个彩色框并将其大小固定为 150 像素。

<!doctype html>
<html lang = "en">
   <style>
      .box{
         font-size:15px;
         padding:15px;
      }
      .box1{background:green; flex-basis:150px; }
      .box2{background:blue; flex-basis:150px;}
      .box3{background:red; flex-basis:150px;}
      
      .container{
         display:flex;
         height:100vh;
         align-items:flex-start;
      }
   </style>
   
   <body>
      <div class = "container">
         <div class = "box box1">One</div>
         <div class = "box box2">two</div>
         <div class = "box box3">three</div>
      </div>
   </body>
</html>

它将产生以下结果 -

弹性增长

我们使用flex-grow属性来设置flex-grow因子。如果容器中空间过多,它会指定特定弹性项目应增长多少。

<!doctype html>
<html lang = "en">
   <style>
      .box{
         font-size:15px;
         padding:15px;
      }
      .box1{background:green; flex-grow:10; flex-basis:100px; }
      .box2{background:blue; flex-grow:1; flex-basis:100px; }
      .box3{background:red; flex-grow:1; flex-basis:100px; }
      
      .container{
         display:flex;
         height:100vh;
         align-items:flex-start;
      }
   </style>
   
   <body>
      <div class = "container">
         <div class = "box box1">One</div>
         <div class = "box box2">two</div>
         <div class = "box box3">three</div>
      </div>
   </body>
</html>

它将产生以下结果 -

弯曲收缩

我们使用flex-shrink属性来设置flex收缩因子。如果容器中没有足够的空间,它会指定弹性项目应收缩的程度。

<!doctype html>
<html lang = "en">
   <style>
      .box{
         font-size:15px;
         padding:15px;
      }
      .box1{background:green; flex-basis:200px; flex-shrink:10}
      .box2{background:blue; flex-basis:200px; flex-shrink:1}
      .box3{background:red; flex-basis:200px; flex-shrink:1}
      
      .container{
         display:flex;
         height:100vh;
         align-items:flex-start;
      }
   </style>
   
   <body>
      <div class = "container">
         <div class = "box box1">One</div>
         <div class = "box box2">two</div>
         <div class = "box box3">three</div>
      </div>
   </body>
</html>

它将产生以下结果 -

柔性

有一个简写可以同时为所有这三个属性设置值;它被称为Flex。使用此属性,您可以一次将值设置为 flex-grow、flex-shrink 和 flex-basis 值。这是该属性的语法。

.item {
   flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}