Flex 布局教程

117

一、Flex 布局教程:语法篇

网页布局(layout) 是 CSS 的重点应用
image.png

传统布局的解决方案基于 盒状模型,依赖 display+float+position
它对于那些特殊布局非常不方便,比如 垂直居中 就不容易实现,而 Flex 布局 却易如反掌
image.png
2009年,W3C 提出了一种新的方案 Flex 布局,可以 简便、完整、响应式 地实现各种页面布局。目前,它已经得到了所有浏览器的支持,这意味着,现在就能很安全地使用这项功能
image.png
Flex 布局将成为未来布局的首选方案。网友JailBreak为本文制作 参考示例演示
参考了这三篇文章


1. Flex 布局是什么?

Flex 是 Flexible Box 的缩写,意为 弹性布局,用来为盒状模型提供最大的灵活性
任何一个容器都可以指定为 Flex 布局

.box{
  display: flex;
}


行内元素也可以使用 Flex 布局

.box{
  display: inline-flex;
}


Webkit 内核的浏览器,必须加上-webkit前缀

.box{
  display: -webkit-flex; /* Safari */
  display: flex;
}

⚠️**注意: **设为 Flex 布局以后,子元素的 float clear 和 vertical-align 属性将失效

2. 基本概念

采用 Flex 布局的元素,称为 Flex 容器(flex container),简称"容器"。它的所有子元素自动成为容器成员,称为 Flex项目(flex item) ,简称"项目"

  • 容器默认存在两根轴:
    • 水平主轴(main axis)
    • 垂直交叉轴(cross axis)
  • 主轴的开始位置(与边框的交叉点)叫 main start,结束位置叫做 main end
  • 交叉轴的开始位置叫做 cross start,结束位置叫 cross end
  • 项目默认沿主轴排列。单个项目占据的主轴空间叫做 main size,占据的交叉轴空间叫做 cross size | | 属性名称 | 属性含义 | 属性可能的值 | | --- | --- | --- | --- | |

    定义在容器的属性 |
    flex-direction |
    决定主轴的方向 | row(默认):水平,起点在左端
    row-reverse:水平,起点在右端
    column:垂直,起点在上沿
    column-reverse:垂直,起点在下沿 | | |
    flex-wrap |
    决定一条轴线放不下,如何换行 | nowrap(默认):不换行
    wrap:换行,第一行在上面
    wrap-reverse:换行,第一行在下面 | | | flex-flow | 上面两个属性简写 | 默认值是 row nowrap | | | justify-content | 定义项目在主轴上的对齐方式 | flex-start:(默认值)左对齐
    flex-end:右对齐
    center:居中
    space-between:两端对齐,项目之间的间隔都相等
    space-around:每个项目之间的间隔相等,所以项目之间的间隔比项目与边框之间的间隔大一倍 | | | align-items | 定义项目在交叉轴上如何对齐 | flex-start:交叉轴的起点对齐
    flex-end:交叉轴的终点对齐
    center:交叉轴的中点对齐
    baseline:项目的第一行文字的基线对齐
    stretch(默认值):如果项目未设置高度或者设为auto,将占满整个容器的高度 | | | align-content | 定义多跟轴线对齐方式,一条轴线该属性不起作用 | flex-start: 与交叉轴的起点对齐
    flex-end:与交叉轴的终点对齐
    center:与交叉轴的中点对齐
    space-between:与交叉轴的两端对齐,轴线之间的间隔平均分布
    space-around:每根轴线之间的间隔都相等,所以轴线之间的间隔比轴线与边框之间的间隔大一倍 | |
    定义在项目上的属性 | order | 定义项目的排列顺序,数值越小,排列越靠前 | 默认0 | | | flex-grow | 定义项目的放大比例,如果存在剩余空间,不放大 | 默认0(如果所有项目的flex-grow属性为1,则等分剩余空间) | | | flex-shrink | 定义项目的缩小比例 | 默认1 负值对该属性无效 | | | flex-basis | 定义在分配多余空间之前,项目占据的主轴空间,浏览器根据这个属性来计算主轴是否有多余空间 | 默认auto,即项目本来大小 | | | flex | 是上面三个的简写 | 默认值 0 1 auto 后两个值可选 | | | align-self | 允许单个项目与其他项目不一样的对齐方式,可覆盖align-items属性 | 默认值auto 表示继承父元素的align-items属性,如果没有父元素,则等同于 stretch |


3. 容器的属性

3.1 flex-direction属性

flex-direction 决定主轴的方向(即项目的排列方向)

.box {
  flex-direction: row | row-reverse | column | column-reverse;
}

image.png

  • row(默认) 主轴为水平方向,起点在左端
  • row-reverse 主轴为水平方向,起点在右端
  • column 主轴为垂直方向,起点在上沿
  • column-reverse 主轴为垂直方向,起点在下

3.2 flex-wrap属性

flex-wrap 定义换行,默认情况下,项目都排在一条线(又称"轴线")上,如果一条轴线排不下,如何换行

.box{
  flex-wrap: nowrap | wrap | wrap-reverse;
}

image.png

  • nowrap (默认) 不换行

image.png

  • wrap 换行,第一行在上方

  • wrap-reverse 换行,第一行在下方


3.3 flex-flow

flex-flow 属性是 flex-direction+flex-wrap 的简写形式,默认值为row nowrap

.box {
  flex-flow: <flex-direction> || <flex-wrap>;
}

3.4 justify-content属性

justify-content 属性定义了项目在主轴上的对齐方式

.box {
  justify-content: flex-start | flex-end | center | space-between | space-around;
}

image.png
它可取5个值,具体对齐方式与轴的方向有关。下面假设主轴为从左到右

  • flex-start(默认) 左对齐
  • flex-end 右对齐
  • center 居中
  • space-between 两端对齐,项间隔都相等
  • space-around 每个项目两侧的间隔相等。所以,项目之间的间隔比项目与边框的间隔大一倍

3.5 align-items属性

align-items 定义项目在交叉轴上如何对齐

.box {
  align-items: flex-start | flex-end | center | baseline | stretch;
}

image.png
它可能取5个值。具体的对齐方式与交叉轴的方向有关,下面假设交叉轴从上到下

  • flex-start 交叉轴的起点对齐
  • flex-end 交叉轴的终点对齐
  • center 交叉轴的中点对齐
  • stretch(默认) 如果项目未设置高度或设为auto,将占满整个容器的高度
  • baseline 项目的第一行文字的基线对齐

3.6 align-content属性

align-content 属性定义了 多根轴线 的对齐方式。如果项目只有一根轴线,该属性不起作用

.box {
  align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}

image.png
该属性可能取6个值

  • flex-start 与交叉轴的起点对齐
  • flex-end 与交叉轴的终点对齐
  • center 与交叉轴的中点对齐
  • stretch(默认) 轴线占满整个交叉轴
  • space-between 与交叉轴两端对齐,轴线之间的间隔平均分布
  • space-around 每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍



4、项目的属性

4.1 order属性

order 属性定义项目的排列顺序
数值越小(可为负值) 排列越靠前,默认0

.item {
  order: <integer>;
}

image.png

4.2 flex-grow属性

flex-grow 属性定义项目的放大比例
默认0 即如果存在剩余空间,也不放大

.item {
  flex-grow: <number>; /* default 0 */
}


如果所有项的 flex-grow 属性都为1,则它们将等分剩余空间(如果有的话)
如果一个项的 flex-grow 属性为2,其他项都为1,则为2占据的剩余空间将比其他项多一倍

4.3 flex-shrink属性

flex-shrink 属性定义了项目的缩小比例,默认为1,即如果空间不足,该项目将缩小

.item {
  flex-shrink: <number>; /* default 1 */
}


如果所有项的 flex-shrink 属性都为1,当空间不足时,都将等比例缩小
如果一个项的 flex-shrink 属性为0,其他项目都为1,则空间不足时,为0的不缩小。负值对该属性无效

4.4 flex-basis属性

flex-basis 属性定义了在分配多余空间之前,项目占据的主轴空间(main size)。浏览器根据这个属性,计算主轴是否有多余空间。它的默认值为 auto,即项目的本来大小

.item {
  flex-basis: <length> | auto; /* default auto */
}

它可以设为跟width或height属性一样的值(比如350px),则项目将占据固定空间

4.5 flex属性

flex 属性是 flex-grow+flex-shrink+flex-basis 的简写,默认值为 0 1 auto 后两个属性可选

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

该属性有两个快捷值: auto (1 1 auto) 和 none (0 0 auto)

  • 建议优先使用这个属性,而不是单独写三个分离的属性,因为浏览器会推算相关值

4.6 align-self属性

align-self 属性允许单个项目有与其他项目不一样的对齐方式,可覆盖 align-items 属性
默认值为auto,表示继承父元素的align-items属性,如果没有父元素,则等同于stretch

.item {
  align-self: auto | flex-start | flex-end | center | baseline | stretch;
}

image.png
该属性可以有6个值,除了auto,其他都与 align-items 属性完全一致






二、Flex 布局教程:实例篇

不管是什么布局,Flex往往都可以几行命令搞定
image.png

1.骰子的布局

骰子的一面,最多可以放置9个点

下面,就来看看Flex如何实现,从1个点到9个点的布局。你可以到 codepen查看Demo

如果不加说明,本节的HTML模板一律如下

<div class="box">
  <span class="item"></span>
</div>

上面代码中,div元素(代表骰子的一个面)是Flex容器,span元素(代表一个点)是Flex项目。如果有多个项目,就要添加多个span元素,以此类推

1.1 单项目

.box {
  display: flex;
}

.box {
  display: flex;
  justify-content: center;
}


![](https://cdn.nlark.com/yuque/0/2020/png/604921/1578315727962-15c4acde-b4db-4e44-9ae9-c5d46f9ca4ba.png#align=left&display=inline&height=111&margin=%5Bobject%20Object%5D&originHeight=222&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; justify-content: flex-end; } ```


![](https://cdn.nlark.com/yuque/0/2020/png/604921/1578315726763-d65cb322-82c8-4c5b-a06d-2fa16022002c.png#align=left&display=inline&height=110&margin=%5Bobject%20Object%5D&originHeight=220&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; align-items: center; } ```


![](https://cdn.nlark.com/yuque/0/2020/png/604921/1578315725739-44839ebb-3193-4101-b8d7-5b834d26bda8.png#align=left&display=inline&height=125&margin=%5Bobject%20Object%5D&originHeight=249&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; justify-content: center; align-items: center; } ```


![](https://cdn.nlark.com/yuque/0/2020/png/604921/1578315728179-0f05f798-3e19-45fb-90f0-59002a357e04.png#align=left&display=inline&height=140&margin=%5Bobject%20Object%5D&originHeight=280&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; justify-content: center; align-items: flex-end; } ```

![](https://cdn.nlark.com/yuque/0/2020/png/604921/1578315727718-ac931e7b-9561-4e1d-937a-a65085e2ad26.png#align=left&display=inline&height=134&margin=%5Bobject%20Object%5D&originHeight=267&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; justify-content: flex-end; align-items: flex-end; } ```

1.2 双项目

.box {
  display: flex;
  justify-content: space-between;
}


![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580826708714-4c25ff34-9c48-40c2-a009-54a9b37c1098.png#align=left&display=inline&height=131&margin=%5Bobject%20Object%5D&originHeight=262&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; flex-direction: column; justify-content: space-between; } ```

![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580826708502-e766fd1d-9e38-45d3-b487-c9bcabdb47b4.png#align=left&display=inline&height=120&margin=%5Bobject%20Object%5D&originHeight=239&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; flex-direction: column; justify-content: space-between; align-items: center; } ```

![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580826709082-e67ceb9f-4018-4fdb-9786-f78384927f57.png#align=left&display=inline&height=134&margin=%5Bobject%20Object%5D&originHeight=268&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; flex-direction: column; justify-content: space-between; align-items: flex-end; } ```

![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580826707902-1d45a7e1-c3dc-4d63-9583-331aea62f6ac.png#align=left&display=inline&height=136&margin=%5Bobject%20Object%5D&originHeight=272&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; } .item:nth-child(2) { align-self: center; } ```


![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580826709637-a03d04b6-9497-40d9-a7bc-ac5719f47f19.png#align=left&display=inline&height=120&margin=%5Bobject%20Object%5D&originHeight=240&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; justify-content: space-between; } .item:nth-child(2) { align-self: flex-end; } ```

1.4 四项目

.box {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-content: space-between;
}



![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580827494493-09cc4bec-4f22-4d6e-927e-65f5caa26e75.png#align=left&display=inline&height=122&margin=%5Bobject%20Object%5D&originHeight=243&originWidth=400&size=0&status=done&style=none&width=200) ```html
``` ```css .box { display: flex; flex-wrap: wrap; align-content: space-between; } .column { flex-basis: 100%; display: flex; justify-content: space-between; } ```

1.5 六项目

.box {
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
}


![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580827611157-8e4db991-9148-45e0-8360-5343ec41f79f.png#align=left&display=inline&height=132&margin=%5Bobject%20Object%5D&originHeight=264&originWidth=400&size=0&status=done&style=none&width=200) ```css .box { display: flex; flex-direction: column; flex-wrap: wrap; align-content: space-between; } ```

![](https://cdn.nlark.com/yuque/0/2020/png/604921/1580827612524-2989d6a5-576c-4224-949d-c13285deddfe.png#align=left&display=inline&height=116&margin=%5Bobject%20Object%5D&originHeight=231&originWidth=400&size=0&status=done&style=none&width=200) ```html
``` ```css .box { display: flex; flex-wrap: wrap; } .row{ flex-basis: 100%; display:flex; } .row:nth-child(2){ justify-content: center; } .row:nth-child(3){ justify-content: space-between; } ```

1.6 九项目

.box {
  display: flex;
  flex-wrap: wrap;
}

1.7旋转的骰子

image.png

<style>
  /*
Flexbox dice by Landon Schropp
http://davidwalsh.name/flexbox-dice

I have just integrate it in my 3D cube
*/

  *,
  *:before,
  *:after {
    box-sizing: border-box;
  }

  body {
    background: #444;
    perspective: 1200px;
    padding-left: 50%;
  }

  /* PREPARING FACES   */
  .preface {
    position: absolute;
    transform: rotateX(45deg);
    transform-style: preserve-3d;
  }

  .preface .face {
    padding: 30px;
    height: 200px;
    width: 200px;
    transform-style: initial;
    border: 1px #333 solid;
    background: rgba(255, 255, 255, 0.9);
    object-fit: contain;
  }

  .pip {
    display: block;
    width: 35px;
    height: 35px;
    border-radius: 50%;
    background-color: #333;
    box-shadow: inset 0 3px #111, inset 0 -3px #555;
  }


  /* 1° FACE  */
  #top .face {
    transform-origin: top;
    transform: translateY(-200px);
    transform: rotateX(90deg);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /* 2° FACE  */
  #front .face {
    transform: translateZ(200px);
    display: flex;
    justify-content: space-between;
  }

  #front .face .pip:nth-of-type(2) {
    align-self: flex-end;
  }

  /* 3° FACE  */
  #bottom .face {
    transform-origin: bottom;
    transform: translateY(200px);
    transform: rotateX(-90deg);
    display: flex;
    justify-content: space-between;
  }

  #bottom .face .pip:nth-of-type(2) {
    align-self: center;
  }

  #bottom .face .pip:nth-of-type(3) {
    align-self: flex-end;
  }

  /* 4° FACE  */
  #back .face {
    display: flex;
    justify-content: space-between;
  }

  #back .face .column {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  /* 5° FACE */
  #left .face {
    transform-origin: left;
    transform: translateX(-200px);
    transform: rotateY(-90deg);
    display: flex;
    justify-content: space-between;
  }

  #left .face .column:nth-of-type(2) {
    justify-content: center;
  }

  #left .face .column {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  /* 6° FACE */
  #right .face {
    transform-origin: right;
    transform: translateX(200px);
    transform: rotateY(90deg);
    display: flex;
    justify-content: space-between;
  }

  #right .face .column {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  section {
    padding-top: 40%;
    transform-origin: 0% 0%;
    animation: spinning 5s ease-in-out 0s infinite alternate;
    transform-style: preserve-3d;
  }

  @keyframes spinning {
    from {
      transform: rotateY(0deg)
    }

    to {
      transform: rotateY(360deg)
    }
  }
</style>

<section class="container">
  <div id="top" class="preface">
    <div class="face">
        <span class="pip"></span>
    </div>
  </div>
  <div id="front" class="preface">
    <div class="face">
        <span class="pip"></span>
        <span class="pip"></span>
    </div>
  </div>
  <div id="bottom" class="preface">
    <div class="face">
        <span class="pip"></span>
        <span class="pip"></span>
        <span class="pip"></span>
    </div>
  </div>
  <div id="back" class="preface">
    <div class="face">
      <div class="column">
          <span class="pip"></span>
          <span class="pip"></span>
        </div>
        <div class="column">
          <span class="pip"></span>
          <span class="pip"></span>
        </div>
    </div>
  </div>
  <div id="left" class="preface">
    <div class="face">
      <div class="column">
        <span class="pip"></span>
        <span class="pip"></span>
      </div>
      <div class="column">
        <span class="pip"></span>
      </div>
      <div class="column">
        <span class="pip"></span>
        <span class="pip"></span>
      </div>
    </div>
  </div>
  <div id="right" class="preface">
    <div class="face">
      <div class="column">
        <span class="pip"></span>
        <span class="pip"></span>
        <span class="pip"></span>
      </div>
      <div class="column">
        <span class="pip"></span>
        <span class="pip"></span>
        <span class="pip"></span>
      </div>
    </div>
  </div>
</section>


2.网格状布局

2.1 基本网格布局

网格状布局在容器里面平均分配空间,跟上面的骰子布局很像,但是需要设置项目的自动缩放

<div class="Grid">
  <div class="Grid-cell">...</div>
  <div class="Grid-cell">...</div>
  <div class="Grid-cell">...</div>
</div>
.Grid {
  display: flex;
}
.Grid-cell {
  flex: 1;
}

2.2 百分比布局

某个网格的宽度为固定的百分比,其余网格平均分配剩余的空间
image.png

<div class="Grid">
  <div class="Grid-cell u-1of4">...</div>
  <div class="Grid-cell">...</div>
  <div class="Grid-cell u-1of3">...</div>
</div>

<style>
.Grid {
  display: flex;
}
.Grid-cell {
  flex: 1;
}
.Grid-cell.u-full {
  flex: 0 0 100%;
}
.Grid-cell.u-1of2 {
  flex: 0 0 50%;
}
.Grid-cell.u-1of3 {
  flex: 0 0 33.3333%;
}
.Grid-cell.u-1of4 {
  flex: 0 0 25%;
}
 </style>

2.3.圣杯布局

圣杯布局(Holy Grail Layout) 指的是一种最常见的网站布局。页面从上到下,分成三个部分:

  • 头部 (header)
  • 躯干 (body)又水平分成三栏,从左到右为:
    • 导航
    • 主栏
    • 副栏
  • 尾部 (footer)

<body class="HolyGrail">
  <header>...</header>
  <div class="HolyGrail-body">
    <main class="HolyGrail-content">...</main>
    <nav class="HolyGrail-nav">...</nav>
    <aside class="HolyGrail-ads">...</aside>
  </div>
  <footer>...</footer>
</body>

<style>
  .HolyGrail {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}
header,
footer {
  flex: 1;
}
.HolyGrail-body {
  display: flex;
  flex: 1;
}
.HolyGrail-content {
  flex: 1;
}
.HolyGrail-nav, .HolyGrail-ads {
  /* 两个边栏的宽度设为12em */
  flex: 0 0 12em;
}
.HolyGrail-nav {
  /* 导航放到最左边 */
  order: -1;
}
<style/>

如果是小屏幕,躯干的三栏自动变为垂直叠加

@media (max-width: 768px) {
  .HolyGrail-body {
    flex-direction: column;
    flex: 1;
  }
  .HolyGrail-nav,
  .HolyGrail-ads,
  .HolyGrail-content {
    flex: auto;
  }
}

2.4.输入框的布局

我们常常需要在输入框的前方添加提示,后方添加按钮

<div class="InputAddOn">
  <span class="InputAddOn-item">...</span>
  <input class="InputAddOn-field">
  <button class="InputAddOn-item">...</button>
</div>

<style>
  .InputAddOn {
  display: flex;
}
.InputAddOn-field {
  flex: 1;
}
</style>

2.5.悬挂式布局

有时,主栏的左侧或右侧,需要添加一个图片栏

<div class="Media">
  <img class="Media-figure" src="" alt="">
  <p class="Media-body">...</p>
</div>

<style>
  .Media {
  display: flex;
  align-items: flex-start;
}
.Media-figure {
  margin-right: 1em;
}
.Media-body {
  flex: 1;
}
</style>

2.6固定的底栏

有时,页面内容太少,无法占满一屏的高度,底栏就会抬高到页面的中间。这时可以采用Flex布局,让底栏总是出现在页面的底部

<body class="Site">
  <header>...</header>
  <main class="Site-content">...</main>
  <footer>...</footer>
</body>
<style>
  .Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}
.Site-content {
  flex: 1;
}
</style>

2.7.流式布局

每行的项目数固定,会自动分行

.parent {
  width: 200px;
  height: 150px;
  background-color: black;
  display: flex;
  flex-flow: row wrap;
  align-content: flex-start;
}
.child {
  box-sizing: border-box;
  background-color: white;
  flex: 0 0 25%;
  height: 50px;
  border: 1px solid red;
}