Flexbox
Build flexible one-dimensional layouts with CSS Flexbox
CSS Flexbox
Flexbox is a one-dimensional layout method for arranging items in rows or columns.
Enabling Flexbox
.container {
display: flex;
}
CSSAll direct children of a flex container become flex items.
Direction
.container {
display: flex;
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 */
}
CSSAlignment
Main Axis (justify-content)
.container {
display: flex;
justify-content: flex-start; /* Pack to the start (default) */
justify-content: flex-end; /* Pack to the end */
justify-content: center; /* Center items */
justify-content: space-between; /* Equal space between items */
justify-content: space-around; /* Equal space around items */
justify-content: space-evenly; /* Truly equal spacing */
}
CSSCross Axis (align-items)
.container {
display: flex;
align-items: stretch; /* Stretch to fill (default) */
align-items: flex-start; /* Align to top */
align-items: flex-end; /* Align to bottom */
align-items: center; /* Center vertically */
align-items: baseline; /* Align text baselines */
}
CSSCentering (the classic problem, solved)
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
CSSWrapping
.container {
display: flex;
flex-wrap: wrap; /* Items wrap to next line when they don't fit */
gap: 1rem; /* Space between items */
}
CSSFlex Items
.item {
flex-grow: 1; /* How much the item should grow */
flex-shrink: 1; /* How much the item should shrink */
flex-basis: 200px; /* Starting size before growing/shrinking */
/* Shorthand: grow shrink basis */
flex: 1 1 200px;
/* Common patterns */
flex: 1; /* Grow equally, shrink equally, basis 0 */
flex: none; /* Don't grow or shrink */
}
CSSPractical Examples
Navigation Bar
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
.nav-links {
display: flex;
gap: 2rem;
list-style: none;
}
CSSCard Grid
.card-container {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.card {
flex: 1 1 300px; /* Grow, shrink, min 300px wide */
max-width: 400px;
}
CSSSticky Footer
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1; /* Takes up all available space */
}
CSS