CSS Flexible Box Layout (Flexbox) is a one-dimensional layout model designed to distribute space dynamically and align items efficiently along rows or columns, even when their dimensions are unknown or dynamically changing. Flexbox revolutionized web development by permanently ending layout hacks and centering struggles.
Flexbox operates on a strict parent-child relationship: styling the Flex Container controls macro alignment, while properties on Flex Items control individual sizing and ordering.
| Property | Standard Values | Layout Function |
|---|---|---|
display: flex |
flex, inline-flex |
Activates the flexbox formatting context for all direct children. |
flex-direction |
row (default), column, row-reverse, column-reverse |
Establishes the Main Axis direction (horizontal row or vertical column). |
justify-content |
flex-start, center, flex-end, space-between, space-around, space-evenly |
Aligns items along the Main Axis (distributes extra horizontal space). |
align-items |
stretch (default), center, flex-start, flex-end, baseline |
Aligns items along the perpendicular Cross Axis (vertical centering). |
flex-wrap |
nowrap (default), wrap, wrap-reverse |
Allows items to break into multiple lines when screen width is constrained. |
gap |
15px, 1rem 2rem |
Defines clean gutters between items without needing margin hacks! |
The flex shorthand combines three powerful child sizing properties:
/* Shorthand Syntax: flex: [flex-grow] [flex-shrink] [flex-basis]; */
.sidebar {
flex: 0 0 300px; /* Never grow, never shrink, fixed 300px width */
}
.main-content {
flex: 1 1 auto; /* Grows to fill all available spare space */
}
Centering an element both horizontally and vertically was the most infamous problem in 1990s and 2000s web development. Flexbox solves it in two simple declarations:
.center-box {
display: flex;
justify-content: center; /* Center along Main Axis */
align-items: center; /* Center along Cross Axis */
height: 300px;
}
.navbar {
display: flex;
justify-content: space-between; /* Brand left, navigation links right */
align-items: center;
padding: 15px 30px;
background-color: #0f172a;
}
.nav-links {
display: flex;
gap: 20px;
list-style: none;
margin: 0;
padding: 0;
}
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Understand margins, borders, padding, content and the universal box-sizing fix.
Build powerful two-dimensional grid layouts with template areas and fr units.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.