Flexbox is the foundation of modern CSS layouts. Master these properties and you can build any 1D layout.
Container Properties
display: flex
Creates a flex container. Direct children become flex items.
flex-direction
.container {
flex-direction: row; /* → default, left to right */
flex-direction: row-reverse; /* ← right to left */
flex-direction: column; /* ↓ top to bottom */
flex-direction: column-reverse; /* ↑ bottom to top */
}justify-content (Main Axis)
.container {
justify-content: flex-start; /* |■ ■ ■ | */
justify-content: center; /* | ■ ■ ■ | */
justify-content: flex-end; /* | ■ ■ ■| */
justify-content: space-between; /* |■ ■ ■| */
justify-content: space-around; /* | ■ ■ ■ | */
justify-content: space-evenly; /* | ■ ■ ■ | */
}align-items (Cross Axis)
.container {
align-items: stretch; /* Items fill container height (default) */
align-items: flex-start; /* Items at top */
align-items: center; /* Items centered vertically */
align-items: flex-end; /* Items at bottom */
align-items: baseline; /* Items aligned by text baseline */
}flex-wrap
.container {
flex-wrap: nowrap; /* All items on one line (default) */
flex-wrap: wrap; /* Items wrap to next line */
}Item Properties
flex shorthand
.item {
flex: 1; /* flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
flex: 0 0 200px; /* Don't grow, don't shrink, 200px wide */
flex: 2 1 auto; /* Grow 2x, can shrink, natural width */
}align-self
.item {
align-self: center; /* Override container's align-items for this item */
}order
.item { order: -1; } /* Move before other items (default is 0) */Common Patterns
/* Centering */
.center {
display: flex;
justify-content: center;
align-items: center;
}
/* Sticky footer */
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main { flex: 1; }
/* Holy grail layout */
.layout {
display: flex;
}
.sidebar { flex: 0 0 250px; }
.content { flex: 1; }
.aside { flex: 0 0 200px; }Gotchas
flex-basisvswidth: flex-basis wins in a flex containermin-width: autois the default for flex items — content can overflow. Usemin-width: 0to allow shrinking- Margin auto absorbs extra space:
margin-left: autopushes items to the right