Flex布局basis、grow、shrink 运用

765 阅读2分钟

前言

在使用 flex 布局的时候大家难以理解的是flex-basisflex-growflex-shrink 几个属性的用法。在平时面试时,大多数人也只能答出flex布局基础的一些用法,当深入问到flex-basisflex-growflex-shrink这三个属性用法时候,大多数人都支支吾吾。下面通过几个例子来详解这三个属性的用法。

flex-basis

flex-basis 用于设置子项的占用空间。如果设置了值,则子项占用的空间为设置的值;如果没设置或者为 auto,那子项的空间为width/height 的值。

A01.png

<div class="box">
  <div class="item">1</div>
  <div class="item">222</div>
  <div class="item">3</div>
</div>
<style>
.box { width: 400px; height: 50px ; display: flex; background-color: #eee ; } 
.item { height: 50px ; } 
.item:nth-child(1) { background: red; }
.item:nth-child(2) { width: 70px; flex-basis: auto; background: grey; } 
.item:nth-child(3) { width: 50px; flex-basis: 100px; background: yellow; }
</style>
  • 对于子项1,flex-basis 如果设置默认是auto,子项占用的宽度使用width 的宽度,width没设置也为 auto,所以子项占用空间由内容决定。
  • 对于子项2,flex-basisauto,子项占用宽度使用width 的宽度,width70px,所以子项子项占用空间是70px
  • 对于子项3,flex-basis100px,覆盖width 的宽度,所以子项占用空间是100px

flex-grow

用来“瓜分”父项的“剩余空间”。

A02.png

<div class="box">
  <div class="item">1</div>
  <div class="item">222</div>
  <div class="item">3</div>
</div>
<style>
.box {
  width: 400px;
  height: 50px;
  display: flex;
  background-color: #eee;
}
. item {
	height: 50px;
}
.item:nth-child(1) {
  width: 50px; 
  background: red;
}
.item:nth-child(2) {
  width: 70px;
  flex-basis: auto;
  flex-grow: 2;
  background: grey;
}
.item:nth-child(3) {
  width: 50px;
  flex-basis: 100px;
  flex-grow: 1;
  background: yellow;
}
</style>

容器的宽度为400px, 子项1的占用的基础空间(flex-basis)为50px,子项2占用的基础空间是70px,子项3占用基础空间是100px,剩余空间为 400-50-70-100=180px。 其中子项1的flex-grow: 0(未设置默认为0), 子项2flex-grow: 2,子项3flex-grow: 1,剩余空间分成3份,子项2占2份(120px),子项3占1份(60px)。所以 子项1真实的占用空间为: 50+0=50px, 子项2真实的占用空间为: 70+120=190px, 子项3真实的占用空间为: 100+60=160px

flex-shrink

用来“吸收”超出的空间

A03.png

<div class="box">
  <div class="item">1</div>
  <div class="item">222</div>
  <div class="item">3</div>
</div>
<style>
.box {
  width: 400px;
  height: 50px;
  display: flex;
  background-color: #eee;
}
.item {
	height: 50px;
}
.item:nth-child(1) {
  width:250px;
  background:red;
}
.item:nth-child(2) {
  width:150px;
  flex-basis: auto;
  flex-shrink: 2;
  background: grey ;
}
.item:nth-child(3) {
  width: 50px;
  flex-basis: 100px;
  flex-shrink: 2;
  background: yellow;
}
</style>

容器的宽度为400px, 子项1的占用的基准空间flex-basis250px,子项2占用的基准空间是150px,子项3占用基准空间是100px,总基准空间为250+150+100=500px。容器放不下,多出来的空间需要被每个子项根据自己设置的flex-shrink 进行吸收。 子项1的flex-shrink: 1(未设置默认为1), 子项2 flex-shrink: 2,子项3 flex-shrink: 2。子项1需要吸收的的空间为 (250*1)/(250*1+150*2+100*2) * 100 = 33.33px,子项1真实的空间为 250-33.33=216.67px。同理子项2吸收的空间为(150*2)/(250*1+150*2+100*2) * 100=40px,子项2真实空间为 150-40 = 110px。子项3吸收的空间为(100*2)/(250*1+150*2+100*2) * 100=26.67px,真实的空间为100-26.67=73.33px