背景
长久以来,唯一可用的且有稳定的跨浏览器兼容性的能用来构建 CSS 布局的工具只有 floats
和 positioning
。它们能够简单且有效地满足大部分布局场景,但是在某些复杂布局方面它们就难以实现了,如:
- 在父内容里面垂直居中一个块内容。
- 使容器的所有子项占用等量的可用宽度/高度,而不管有多少宽度/高度可用。
- 使多列布局中的所有列采用相同的高度,即使它们包含的内容量不同。
基本属性
Since flexbox is a whole module and not a single property, it involves a lot of things including its whole set of properties. Some of them are meant to be set on the container (parent element, known as “flex container”) whereas the others are meant to be set on the children (said “flex items”).
🥑 flex container 属性
1️⃣ display
This defines a flex container; inline or block depending on the given value. It enables a flex context for all its direct children.
1 | .container { |
2️⃣ flex-direction
1 | .container { |
-
nowrap
(default): all flex items will be on one line-
wrap
: flex items will wrap onto multiple lines, from top to bottom.-
wrap-reverse
: flex items will wrap onto multiple lines from bottom to top.3️⃣ flex-wrap
1 | .container{ |
4️⃣ flex-flow
(Applies to: parent flex container element)
This is a shorthand for the
flex-direction
and flex-wrap
properties, which together define the flex container’s main and cross axes. The default value is row nowrap
.1 | flex-flow: <‘flex-direction’> || <‘flex-wrap’> |
5️⃣ justify-content
1 | .container { |
6️⃣ align-items
1 | .container { |
7️⃣ align-content
1 | .container { |
🥝 flex items 属性
1️⃣ order
1 | .item { |
By default, flex items are laid out in the source order. However, the
order
property controls the order in which they appear in the flex container.2️⃣ flex-grow
1 | .item { |
3️⃣ flex-shrink
This defines the ability for a flex item to shrink if necessary.
1 | .item { |
4️⃣ flex-basis
This defines the default size of an element before the remaining space is distributed. It can be a length (e.g. 20%, 5rem, etc.) or a keyword. The
auto
keyword means “look at my width or height property” (which was temporarily done by the main-size
keyword until deprecated). The content
keyword means “size it based on the item’s content” - this keyword isn’t well supported yet, so it’s hard to test and harder to know what its brethren max-content
, min-content
, and fit-content
do.5️⃣ flex
This is the shorthand for
flex-grow
, flex-shrink
and flex-basis
combined. The second and third parameters (flex-shrink
and flex-basis
) are optional. Default is 0 1 auto
.1 | .item { |
It is recommended that you use this shorthand property
6️⃣ align-self
1 | .item { |
什么时候用 flex 布局和 grid 布局
Flexbox layout is most appropriate to the components of an application, and small-scale layouts, while the Grid layout is intended for larger scale layouts.
相关链接
A Complete Guide to Flexbox
Flexbox
CSS layout
Flex 布局教程:语法篇
Flex 布局教程:实例篇
Flexbox 布局的最简单表单
深入理解css3中的flex-grow、flex-shrink、flex-basis
学习CSS布局
使用 CSS 弹性盒子
Solved by Flexbox