Our comprehensive guide to CSS flexbox layout. This complete guide explains everything about flexbox, focusing on all the different possible properties for the parent element (the flex container) and the child elements (the flex items). It also includes history, demos, patterns, and a browser support chart.
Background
The Flexbox Layout
(Flexible Box) module (a W3C Candidate Recommendation as of October 2017 19 November 2018) aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic (thus the word “flex”).
The main idea behind the flex layout is to give the container the ability to alter its items’ width/height (and order) to best fill the available space (mostly to accommodate to all kind of display devices and screen sizes). A flex container expands items to fill available free space or shrinks them to prevent overflow.
Most importantly, the flexbox layout is direction-agnostic as opposed to the regular layouts (block which is vertically-based and inline which is horizontally-based). While those work well for pages, they lack flexibility (no pun intended) to support large or complex applications (especially when it comes to orientation changing, resizing, stretching, shrinking, etc.).
Note: 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.
Basics & Terminology
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”).
If “regular” layout is based on both block and inline flow directions, the flex layout is based on “flex-flow directions”. Please have a look at this figure from the specification, explaining the main idea behind the flex layout.
Items will be laid out following either the main axis
(from main-start
to main-end
) or the cross axis
(from cross-start
to cross-end
).
- main axis(主轴) – The main axis of a flex container is the primary axis along which flex items are laid out. Beware, it is not necessarily horizontal; it depends on the
flex-direction
property (see below). - main-start | main-end – The flex items are placed within the container starting from main-start and going to main-end.
- main size – A flex item’s width or height, whichever is in the main dimension, is the item’s main size. The flex item’s main size property is either the ‘width’ or ‘height’ property, whichever is in the main dimension.
- cross axis(交叉轴)(和主轴 main axis 垂直) – The axis perpendicular to the main axis is called the cross axis. Its direction depends on the main axis direction.
- cross-start | cross-end – Flex lines are filled with items and placed into the container starting on the cross-start side of the flex container and going toward the cross-end side.
- cross size – The width or height of a flex item, whichever is in the cross dimension, is the item’s cross size. The cross size property is whichever of ‘width’ or ‘height’ that is in the cross dimension.
Flexbox properties
Properties for the Parent(flex container)
display
This defines a flex container; inline or block depending on the given value. It enables a flex context for all its direct children.
.container {
display: flex; /* or inline-flex */
}
Note that CSS columns have no effect on a flex container.
flex-direction
This establishes the main-axis, thus defining the direction flex items are placed in the flex container. Flexbox is (aside from optional wrapping) a single-direction layout concept. Think of flex items as primarily laying out either in horizontal rows or vertical columns.
flex-direction
属性指定了内部元素是如何在 flex 容器中布局的,定义了主轴的方向
.container {
flex-direction: row; /* 从左到右 */
flex-direction: row-reverse; /* 从右到左 */
flex-direction: column; /* 从上到下 */
flex-direction: column-reverse; /* 从下到上 */
}
row
(default): left to right inltr
; right to left inrtl
.row-reverse
: right to left inltr
; left to right inrtl
.column
: same asrow
but top to bottom.column-reverse
: same asrow-reverse
but bottom to top.
flex-wrap
By default, flex items will all try to fit onto one line. You can change that and allow the items to wrap as needed with this property.
flex-wrap
指定 flex 元素单行显示还是多行显示 . 如果允许换行,这个属性允许你控制行的堆叠方向。
.container {
flex-wrap: nowrap; /* flex 的元素被摆放到到一行 单行显示,这可能导致溢出 flex 容器。*/
flex-wrap: wrap; /* flex 元素 被打断到多个行中 多行显示 */
flex-wrap: wrap-reverse; /* 和 wrap 的行为一样,但是从下到上 */
}
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.
There are some visual demos of flex-wrap
here.
flex-flow
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
.
flex-flow
属性是flex-direction
和flex-wrap
的简写
justify-content
This defines the alignment along the main axis. It helps distribute extra free space leftover when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line.
justify-content
属性定义了分配顺着弹性容器主轴的元素之间及其周围的空间。
.container {
justify-content: center; /* 居中排列 */
justify-content: flex-start; /* 从行首起始位置开始排列 */
justify-content: flex-end; /* 从行尾位置开始排列 */
justify-content: space-between; /* 均匀排列每个元素首个元素放置于起点,末尾元素放置于终点 */
justify-content: space-around; /* 均匀排列每个元素每个元素周围分配相同的空间 */
justify-content: space-evenly; /* 均匀排列每个元素每个元素之间的间隔相等 */
}
flex-start
(default): items are packed toward the start of the flex-direction.flex-end
: items are packed toward the end of the flex-direction.start
: items are packed toward the start of thewriting-mode
direction.end
: items are packed toward the end of thewriting-mode
direction.left
: items are packed toward left edge of the container, unless that doesn’t make sense with theflex-direction
, then it behaves likestart
.right
: items are packed toward right edge of the container, unless that doesn’t make sense with theflex-direction
, then it behaves likestart
.center
: items are centered along the line(居中排列)space-between
: items are evenly distributed in the line; first item is on the start line, last item on the end line.space-around
: items are evenly distributed in the line with equal space around them. Note that visually the spaces aren’t equal, since all the items have equal space on both sides. The first item will have one unit of space against the container edge, but two units of space between the next item because that next item has its own spacing that applies.space-evenly
: items are distributed so that the spacing between any two items (and the space to the edges) is equal.
Note that that browser support for these values is nuanced. For example, space-between
never got support from some versions of Edge, and start/end/left/right aren’t in Chrome yet. MDN has detailed charts. The safest values are flex-start
, flex-end
, and center
.
There are also two additional keywords you can pair with these values: safe
and unsafe
. Using safe
ensures that however you do this type of positioning, you can’t push an element such that it renders off-screen (e.g. off the top) in such a way the content can’t be scrolled too (called “data loss”).
align-items
This defines the default behavior for how flex items are laid out along the cross axis on the current line. Think of it as the justify-content
version for the cross-axis (perpendicular to the main-axis).
align-items
controls the alignment of items on the Cross Axis.
.container {
align-items: flex-start; /* Pack flex items from the start */
align-items: flex-end; /* Pack flex items from the end */
align-items: center; /* Pack items around the center */
align-items: stretch;
align-items: baseline;
}
stretch
(default): stretch to fill the container (still respect min-width/max-width)flex-start
/start
/self-start
: items are placed at the start of the cross axis. The difference between these is subtle, and is about respecting theflex-direction
rules or thewriting-mode
rules.flex-end
/end
/self-end
: items are placed at the end of the cross axis. The difference again is subtle and is about respectingflex-direction
rules vs.writing-mode
rules.center
: items are centered in the cross-axisbaseline
: items are aligned such as their baselines align
The safe
and unsafe
modifier keywords can be used in conjunction with all the rest of these keywords (although note browser support), and deal with helping you prevent aligning elements such that the content becomes inaccessible.
align-content
This aligns a flex container’s lines within when there is extra space in the cross-axis, similar to how justify-content
aligns individual items within the main-axis.
align-content
属性设置了浏览器如何沿着 弹性盒子布局 的纵轴和 网格布局 的主轴在内容项之间和周围分配空间。
Note: this property has no effect when there is only one line of flex items.
Note: This property only takes effect on multi-line flexible containers, where flex-flow is set to either wrap or wrap-reverse). A single-line flexible container (i.e. where flex-flow is set to its default value, no-wrap) will not reflect align-content.
.container {
align-content: flex-start; /* Pack flex items from the start */
align-content: flex-end; /* Pack flex items from the end */
align-content: center; /* Pack items around the center */
align-content: space-between; /* Distribute items evenly The first item is flush with the start, the last is flush with the end */
align-content: space-around; /* Distribute items evenly Items have a half-size space on either end */
align-content: space-evenly; /* Distribute items evenly Items have equal space around them */
}
flex-start
/start
: items packed to the start of the container. The (more supported)flex-start
honors theflex-direction
whilestart
honors thewriting-mode
direction.flex-end
/end
: items packed to the end of the container. The (more support)flex-end
honors theflex-direction
while end honors thewriting-mode
direction.center
: items centered in the container(将项目放置在中点)space-between
: items evenly distributed; the first line is at the start of the container while the last one is at the end(均匀分布项目第一项与起始点齐平,最后一项与终止点齐平)space-around
: items evenly distributed with equal space around each line(均匀分布项目项目在两端有一半大小的空间)space-evenly
: items are evenly distributed with equal space around them(均匀分布项目项目周围有相等的空间)stretch
(default): lines stretch to take up the remaining space
The safe
and unsafe
modifier keywords can be used in conjunction with all the rest of these keywords (although note browser support), and deal with helping you prevent aligning elements such that the content becomes inaccessible.
Properties for the Children(flex items)
order
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.
order
属性规定了弹性容器中的可伸缩项目在布局时的顺序。元素按照order
属性的值的增序进行布局
.item {
order: 5; /* default is 0 */
order: -5; /* <integer> values */
}
flex-grow
This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.
If all items have flex-grow
set to 1, the remaining space in the container will be distributed equally to all children. If one of the children has a value of 2, the remaining space would take up twice as much space as the others (or it will try to, at least).
flex-grow
设置弹性项目在主轴的弹性放大比例。
.item {
flex-grow: 4; /* Negative values are invalid. Defaults to 0. */
}
Negative numbers are invalid.
flex-shrink
This defines the ability for a flex item to shrink if necessary.
flex-shrink
设置弹性项目在主轴的弹性缩小比例。
.item {
flex-shrink: 3; /* Negative values are invalid. Defaults to 1. */
}
Negative numbers are invalid.
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.
flex-basis
指定了 flex 元素在主轴方向上的初始大小。
.item {
/* Specify <'width'> */
flex-basis: 10em;
flex-basis: 3px;
flex-basis: auto; /* default auto */
/* Intrinsic sizing keywords */
flex-basis: fill;
flex-basis: max-content;
flex-basis: min-content;
flex-basis: fit-content;
/* Automatically size based on the flex item's content */
flex-basis: content;
}
If set to 0
, the extra space around content isn’t factored in. If set to auto
, the extra space is distributed based on its flex-grow
value.See this graphic.
如果设置为
0
, 则不考虑内容周围的多余空间。如果设置为auto
, 则多余的空间将根据其flex-grow
值进行分配。
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. The default is 0 1 auto
, but if you set it with a single number value, it’s like 1 0
.
flex
规定了弹性元素如何伸长或缩短以适应 flex 容器中的可用空间。这是一个简写属性,用来设置flex-grow
,flex-shrink
与flex-basis
.item {
/* Keyword values */
flex: auto;
flex: initial;
flex: none;
/* One value, unitless number: flex-grow */
flex: 2;
/* One value, width/height: flex-basis */
flex: 10em;
flex: 30%;
flex: min-content;
/* Two values: flex-grow | flex-basis */
flex: 1 30px;
/* Two values: flex-grow | flex-shrink */
flex: 2 2;
/* Three values: flex-grow | flex-shrink | flex-basis */
flex: 2 2 10%;
}
It is recommended that you use this shorthand property rather than set the individual properties. The shorthand sets the other values intelligently.
align-self
This allows the default alignment (or the one specified by align-items
) to be overridden for individual flex items.
align-self
属性设置项目在其包含块中在交叉轴方向上的对齐方式 (覆盖网格或弹性项目的align-items
值)
Please see the align-items
explanation to understand the available values.
.item {
/* Keyword values */
align-self: auto;
align-self: normal;
/* Positional alignment */
/* align-self does not take left and right values */
align-self: center; /* Put the item around the center */
align-self: start; /* Put the item at the start */
align-self: end; /* Put the item at the end */
align-self: self-start; /* Align the item flush at the start */
align-self: self-end; /* Align the item flush at the end */
align-self: flex-start; /* Put the flex item at the start */
align-self: flex-end; /* Put the flex item at the end */
/* Baseline alignment */
align-self: baseline;
}
Note that float
, clear
and vertical-align
have no effect on a flex item.
Examples
Let’s start with a very very simple example, solving an almost daily problem: perfect centering. It couldn’t be any simpler if you use flexbox.
让我们从一个非常简单的示例开始,解决几乎一个日常问题:完美居中。如果使用 flexbox, 再简单不过了。
.parent {
display: flex;
height: 300px; /* Or whatever */
}
.child {
width: 100px; /* Or whatever */
height: 100px; /* Or whatever */
margin: auto; /* Magic! */
}
<div class="flex-container"> <div class="flex-item">1</div> <div class="flex-item">2</div> <div class="flex-item">3</div> <div class="flex-item">4</div> </div>
.flex-container { display: flex; height: 200px; /* Or whatever */ border: 1px solid red; } .flex-item { width: 100px; /* Or whatever */ height: 100px; /* Or whatever */ margin: auto; /* Magic! */ border: 1px solid red; }
This relies on the fact a margin set to auto
in a flex container absorb extra space. So setting a vertical margin of auto
will make the item perfectly centered in both axes.
Now let’s use some more properties. Consider a list of 6 items, all with fixed dimensions, but can be auto-sized. We want them to be evenly distributed on the horizontal axis so that when we resize the browser, everything scales nicely, and without media queries.
.flex-container {
/* We first create a flex layout context */
display: flex;
/* Then we define the flow direction
and if we allow the items to wrap
* Remember this is the same as:
* flex-direction: row;
* flex-wrap: wrap;
*/
flex-flow: row wrap;
/* Then we define how is distributed the remaining space */
justify-content: space-around;
}
Done. Everything else is just some styling concern. Below is a pen featuring this example. Be sure to go to CodePen and try resizing your windows to see what happens.
使用 Flexbox 实现九宫格布局
<div class="flex-container"> <div class="flex-item">1</div> <div class="flex-item">2</div> <div class="flex-item">3</div> <div class="flex-item">4</div> <div class="flex-item">5</div> <div class="flex-item">6</div> <div class="flex-item">7</div> <div class="flex-item">8</div> <div class="flex-item">9</div> </div>
.flex-container { display: flex; flex-flow: row wrap; justify-content: space-around; } .flex-item { background: tomato; padding: 1%; width: 31%; height: 150px; margin-top: 10px; line-height: 150px; color: white; font-size: 3em; text-align: center; }
Let’s try something else. Imagine we have a right-aligned navigation element on the very top of our website, but we want it to be centered on medium-sized screens and single-columned on small devices. Easy enough.
/* Large */
.navigation {
display: flex;
flex-flow: row wrap;
/* This aligns items to the end line on main-axis */
justify-content: flex-end;
}
/* Medium screens */
@media all and (max-width: 800px) {
.navigation {
/* When on medium sized screens, we center it by evenly distributing empty space around items */
justify-content: space-around;
}
}
/* Small screens */
@media all and (max-width: 500px) {
.navigation {
/* On small screens, we are no longer using row direction but column */
flex-direction: column;
}
}
<ul class="navigation"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Products</a></li> <li><a href="#">Contact</a></li> </ul>
.navigation { display: flex; flex-flow: row wrap; justify-content: flex-end; list-style: none; margin: 0; background: deepskyblue; } .navigation a { text-decoration: none; display: block; padding: 1em; color: white; } .navigation a:hover { background: #1565C0; } @media all and (max-width: 800px) { .navigation { justify-content: space-around; } } @media all and (max-width: 600px) { .navigation { flex-flow: column wrap; padding: 0; } .navigation a { text-align: center; padding: 10px; border-top: 1px solid rgba(255, 255, 255,0.3); border-bottom: 1px solid rgba(0, 0, 0, 0.1); } .navigation li:last-of-type a { border-bottom: none; } }
Let’s try something even better by playing with flex items flexibility! What about a mobile-first 3-columns layout with full-width header and footer. And independent from source order.
.wrapper {
display: flex;
flex-flow: row wrap;
}
/* We tell all items to be 100% width, via flex-basis */
.wrapper > * {
flex: 1 100%;
}
/* We rely on source order for mobile-first approach
* in this case:
* 1. header
* 2. article
* 3. aside 1
* 4. aside 2
* 5. footer
*/
/* Medium screens */
@media all and (min-width: 600px) {
/* We tell both sidebars to share a row */
.aside {
flex: 1 auto;
}
}
/* Large screens */
@media all and (min-width: 800px) {
/* We invert order of first sidebar and main
* And tell the main element to take twice as much width as the other two sidebars
*/
.main {
flex: 2 0px;
}
.aside-1 {
order: 1;
}
.main {
order: 2;
}
.aside-2 {
order: 3;
}
.footer {
order: 4;
}
}
<div class="wrapper"> <header class="header">Header</header> <article class="main"> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p> </article> <aside class="aside aside-1">Aside 1</aside> <aside class="aside aside-2">Aside 2</aside> <footer class="footer">Footer</footer> </div>
.wrapper { display: flex; flex-flow: row wrap; text-align: center; } .wrapper > * { padding: 10px; flex: 1 100%; } .header { background: tomato; } .footer { background: lightgreen; } .main { text-align: left; background: deepskyblue; } .aside-1 { background: gold; } .aside-2 { background: hotpink; } @media all and (min-width: 600px) { .aside {flex: 1 0 0;} } @media all and (min-width: 800px) { .main {flex: 3 0px;} .aside-1 {order: 1;} .main {order: 2;} .aside-2 {order: 3;} .footer {order: 4;} } body { padding: 2em; }
Flexbox Tricks
- Adaptive Photo Layout with Flexbox
- Balancing on a Pivot with Flexbox
- Using Flexbox and text ellipsis together
- Useful Flexbox Technique: Alignment Shifting Wrapping
- Designing A Product Page Layout with Flexbox
- Flexbox and Truncated Text
- Flexbox and absolute positioning
- Filling the Space in the Last Row with Flexbox
Prefixing Flexbox
Flexbox requires some vendor prefixing to support the most browsers possible. It doesn’t just include prepending properties with the vendor prefix, but there are actually entirely different property and value names. This is because the Flexbox spec has changed over time, creating an “old”, “tweener”, and “new” versions.
Perhaps the best way to handle this is to write in the new (and final) syntax and run your CSS through Autoprefixer, which handles the fallbacks very well.
Alternatively, here’s a Sass @mixin
to help with some of the prefixing, which also gives you an idea of what kind of things need to be done:
@mixin flexbox() {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
}
@mixin flex($values) {
-webkit-box-flex: $values;
-moz-box-flex: $values;
-webkit-flex: $values;
-ms-flex: $values;
flex: $values;
}
@mixin order($val) {
-webkit-box-ordinal-group: $val;
-moz-box-ordinal-group: $val;
-ms-flex-order: $val;
-webkit-order: $val;
order: $val;
}
.wrapper {
@include flexbox();
}
.item {
@include flex(1 200px);
@include order(2);
}
Related Properties
- A Complete Guide to Grid
- gap
- grid-row / grid-column
- grid-template-columns / grid-template-rows
- justify-items
- place-items The CSS
place-items
shorthand property allows you to align items along both the block and inline directions at once (i.e. thealign-items
andjustify-items
properties) in a relevant layout system such as Grid or Flexbox. If the second value is not set, the first value is also used for it.
In flexbox layouts,
justify-items
property is ignored (more about alignment in Flexbox)
Other Resources
- Flexbox in the CSS specifications
- Basic concepts of flexbox - CSS: Cascading Style Sheets | MDN
- Flexbox - Learn web development | MDN
- Flex - MDN Web Docs Glossary: Definitions of Web-related terms | MDN
- Flexbox at Opera
- Diving into Flexbox by Bocoup
- Mixing syntaxes for best browser support on CSS-Tricks
- Flexbox by Raphael Goetter (FR)
- Flexplorer by Bennett Feely
Bugs
Flexbox is certainly not without its bugs. The best collection of them I’ve seen is Philip Walton and Greg Whitworth’s Flexbugs. It’s an open-source place to track all of them, so I think it’s best to just link to that.