CSS Layout
CSS Flexbox
Build flexible, responsive layouts with CSS Flexbox — the most useful CSS feature for modern web design.
CSS Flexbox
Flexbox is a one-dimensional layout method for arranging items in rows or columns. Items flex to fill additional space and shrink to fit into smaller spaces.
Flex Container Properties
display: flex— creates a flex containerflex-direction— row | column | row-reverse | column-reversejustify-content— alignment on main axisalign-items— alignment on cross axisgap— space between itemsflex-wrap— allow items to wrap
Flex Item Properties
flex— shorthand for grow, shrink, basisalign-self— override align-items for single itemorder— control order of items
When to Use Flexbox
Use flexbox for one-dimensional layouts (one row OR one column). For two-dimensional layouts (rows AND columns simultaneously), use CSS Grid.
Example
css
/* Navigation bar with flexbox */
nav {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 0 24px;
}
/* Card grid with wrap */
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 24px;
}
.card {
flex: 1 1 300px; /* grow shrink basis */
min-width: 0; /* prevent overflow
}
/* Center content vertically and horizontally */
.hero {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Push item to end */
.header {
display: flex;
align-items: center;
}
.header .spacer { flex: 1; } /* or: margin-left: auto */
/* Responsive sidebar layout */
.layout {
display: flex;
gap: 32px;
}
.sidebar { flex: 0 0 260px; }
.main { flex: 1; min-width: 0; }Try it yourself — CSS