Flexbox
A one-dimensional CSS layout model that flexibly distributes space, sizing, and alignment along a single row or column axis
Table of Contents
Interactive Playground
Tap or drag to interact with the demoWhat is Flexbox?
A one-dimensional CSS layout model that flexibly distributes space, sizing, and alignment along a single row or column axis. It is a core concept in Layout & Responsive within UI / UX.
Core Principles
Flexbox (CSS Flexible Box Layout) is a one-dimensional layout system designed to align items and distribute available space along a Main Axis and a perpendicular Cross Axis. By setting flex-direction, you establish the flow direction, then control positioning with justify-content (main axis) and align-items (cross axis).
Individual children adapt fluidly to viewport changes through three sizing properties: flex-grow (how extra space is claimed), flex-shrink (how items compress when space is tight), and flex-basis (the initial size before distribution).
Practical Takeaways
- Pair Flexbox (1D) with CSS Grid (2D): Use Flexbox for single-axis flows like navbars, toolbars, and icon-plus-label alignment; use CSS Grid when rows and columns must align simultaneously across a page shell or dashboard.
- Watch out for
min-width: 0on overflowing children: Flex items default tomin-width: auto, which prevents long unbroken text from shrinking inside a flex container. Addmin-width: 0(min-w-0) so ellipsis truncation andoverflow: hiddenwork as expected. - Prefer
gapover child margins: Usinggapon the flex container avoids awkward trailing margins when items wrap withflex-wrap: wrapand keeps spacing symmetrical.
Notable Examples
- Application headers: Positioning a brand logo on the left, links in the center, and user actions on the right with
justify-content: space-between. - Responsive tag and filter clouds: Combining
flex-wrap: wrapwithgapso variable-width chips flow naturally onto multiple lines. - Component internals: Vertically centering icons next to text, or pinning card footers to the bottom using
flex-direction: columnandmargin-top: auto.
Practical Code Snippet
Copy and drop straight into your project.navbar { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap;} .navbar__search { flex: 1 1 240px; /* grow, shrink, min basis */ max-width: 420px;}