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;
}
CSS

All 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 */
}
CSS

Alignment

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 */
}
CSS

Cross 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 */
}
CSS

Centering (the classic problem, solved)

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}
CSS

Wrapping

.container {
    display: flex;
    flex-wrap: wrap;  /* Items wrap to next line when they don't fit */
    gap: 1rem;        /* Space between items */
}
CSS

Flex 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 */
}
CSS

Practical Examples

.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 2rem;
}

.nav-links {
    display: flex;
    gap: 2rem;
    list-style: none;
}
CSS

Card Grid

.card-container {
    display: flex;
    flex-wrap: wrap;
    gap: 1.5rem;
}

.card {
    flex: 1 1 300px; /* Grow, shrink, min 300px wide */
    max-width: 400px;
}
CSS
body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

main {
    flex: 1; /* Takes up all available space */
}
CSS