Skip to content

    Frontend System Design

    Modern CSS Layout: Flexbox, Grid and Container Queries

    Choose between flexbox and grid, build fluid layouts with minmax, clamp and container queries, and reflow pages at any width without a breakpoint per device.

    By Published 12 min read

    • frontend-system-design
    • css-layout
    • flexbox
    • css-grid
    • container-queries
    Share

    Standard lessonbeginnerFrontend System Design

    Before this: CSS Architecture: the Cascade, Layers, Methodologies and Utility-First

    What you'll learn: By the end of this lesson you will be able to choose between flexbox and grid for a given layout, size grid tracks with fr, repeat() and minmax(), align nested content with subgrid, decide when a media query or a container query is the right tool, scale type with clamp() without breaking zoom, avoid common viewport traps (vh, the viewport meta element), and test a layout against the WCAG reflow rule.

    Think of arranging furniture. A bookshelf wall is one-dimensional: books sit in a row and you only decide how the space along it is shared. A floor plan is two-dimensional: rooms have a width and a length, and walls must line up. Flexbox is the bookshelf and grid is the floor plan. The common mistake is drawing a separate floor plan for every phone and tablet instead of describing rules that fit any room.

    The running example is the product listing page of a grocery marketplace (the front end of the ShopStream marketplace used in this course): a header, a filter sidebar, a grid of product cards, and the same product card reused in a "recently viewed" strip and in a cart upsell panel.

    The core idea

    1. Flexbox lays out items along one axis; grid lays out rows and columns together. Pick by whether the layout has one dimension or two.
    2. Describe constraints, not devices. minmax(), clamp() and repeat(auto-fill, ...) say "at least this wide, at most that wide" and let the browser compute the rest at every width.
    3. A component should respond to its container, not the screen. Media queries ask about the viewport. Container queries ask about the space a component actually has, which is what a reusable card needs.

    Flexbox: one axis at a time

    MDN describes flexbox as a one-dimensional layout model for distributing space between items: it deals with layout in one dimension at a time, as a row or as a column. The main axis is set by flex-direction (default row), and the cross axis runs perpendicular to it.

    Three properties decide how items share the main axis. Their defaults, per MDN: flex-grow is 0, flex-shrink is 1, flex-basis is auto (the browser looks at the item's own size). With a positive flex-grow an item grows from its basis into free space; with a positive flex-shrink it can become smaller than its basis when there is not enough room. flex-wrap defaults to nowrap: all items stay in one row, and MDN notes they overflow the container if their combined size exceeds it. Set flex-wrap: wrap to let them break onto new lines.

    Flexbox suits a header, a toolbar, a row of tags, or centring one thing inside another. It is a poor tool for aligning items across rows.

    Illustration 1: the minimal example

    A toolbar where the search box takes the free space and the other items keep their size:

    .toolbar {
      display: flex;
      gap: 1rem;
      align-items: center;
    }
    .toolbar .search {
      flex: 1 1 auto;
    }

    flex: 1 1 auto sets grow, shrink and basis in that order. The other items keep the default flex-grow: 0, so only the search box takes the free space.

    Grid: rows and columns together

    CSS grid is a two-dimensional system. You define tracks with grid-template-columns and grid-template-rows (the explicit grid); content placed outside that creates implicit tracks, which are auto-sized unless you set grid-auto-rows or grid-auto-columns. The fr unit is a fraction of the available space in the grid container, and gaps (gap, row-gap, column-gap) are taken into account before space is assigned to fr tracks. repeat(3, 1fr) writes three equal tracks, and minmax(100px, auto) gives a track a floor and a ceiling.

    The part that removes breakpoints is repeat() with auto-fill or auto-fit. MDN says auto-fill resolves to the largest number of repetitions that does not cause overflow of a constrained container, and auto-fit behaves the same except that empty repeated tracks collapse to 0px after items are placed. In practice, repeat(auto-fill, minmax(220px, 1fr)) means "as many columns of at least 220px as fit, sharing the leftover space".

    Subgrid. A grid item can itself be a grid, but by default its tracks are independent of the parent's, which makes it hard to align nested content with the outer grid. MDN says that with grid-template-columns: subgrid (or rows) the nested grid uses the tracks of the parent. For product cards, the title, price and button of every card can sit on the same row lines even when titles wrap differently. MDN lists subgrid as Baseline widely available, since September 2023.

    Figure 1. Flexbox or grid?

    flowchart TD accTitle: Choosing between flexbox and grid accDescr: A decision flow. If items only need to be distributed along one axis, such as a toolbar or a row of tags, use flexbox. If rows and columns must line up together, use grid. If the number of columns should change with the available width, use grid with repeat and minmax. If nested content must align to the parent tracks, use subgrid. A{"One axis,
    or rows and columns
    that must line up?"} A -->|"one axis"| B["Flexbox
    toolbar, tags, centring"] A -->|"two axes"| C["Grid"] C --> D{"Columns should
    change with width?"} D -->|"yes"| E["repeat(auto-fill,
    minmax(min, 1fr))"] D -->|"no"| F["fixed tracks
    with fr units"] E --> G{"Nested content
    must align?"} F --> G G -->|"yes"| H["subgrid"] G -->|"no"| I["done"]

    How to read this: start from the shape of the layout, not a device. The two grid questions are independent: column count, and alignment inside each cell.

    Illustration 2: the realistic example

    The product grid of the listing page:

    .product-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      gap: 16px;
    }

    To see what the rule asks for at different widths, here is a small model of it: the largest number of columns of at least 220px with a 16px gap that fit, with the leftover space shared equally (fr). The program models the rule MDN states; it does not run a browser. Run in Node:

    // Model of grid-template-columns: repeat(auto-fill, minmax(min, 1fr)) with a column gap.
    // Largest count n such that n * min + (n - 1) * gap <= width, at least 1; leftover space is shared by 1fr.
    function columns(width, min, gap) {
      const n = Math.max(1, Math.floor((width + gap) / (min + gap)));
      const track = (width - (n - 1) * gap) / n;
      return { n, track: Math.round(track * 10) / 10 };
    }
    for (const width of [320, 600, 768, 1024, 1280]) {
      const { n, track } = columns(width, 220, 16);
      console.log(`container ${String(width).padStart(4)}px -> ${n} column(s) of ${track}px`);
    }

    Output, from running it in Node 26.13.1:

    container  320px -> 1 column(s) of 320px
    container  600px -> 2 column(s) of 292px
    container  768px -> 3 column(s) of 245.3px
    container 1024px -> 4 column(s) of 244px
    container 1280px -> 5 column(s) of 243.2px

    There is no breakpoint in the CSS, yet the column count changes with the width. A new width (a foldable, a narrow window, a zoomed page) is handled for free.

    Responsive design: viewport, media and container

    The viewport meta element. MDN says some mobile browsers render a page in a virtual window wider than the screen and shrink it down, and the viewport <meta> element mitigates that. Its recommended setting is <meta name="viewport" content="width=device-width" />; initial-scale=1 is usually unnecessary. MDN warns that disabling zoom with user-scalable=no prevents people with low vision from reading the page, and notes WCAG requires at least 2x scaling.

    Media queries apply styles depending on the viewport or on user preferences. Use min-width and max-width, or the range syntax such as @media (width >= 600px) and @media (30em < width < 50em); the two forms are equivalent. Media features also cover preferences such as prefers-reduced-motion, and hover: hover for devices whose primary input can hover. Use them for the page shell: is the sidebar beside or above the content?

    Container queries apply styles based on the size of a container. You mark an ancestor with container-type (inline-size queries the inline dimension; size queries both; normal, the default, makes no size container), optionally a container-name, and write @container (width > 700px) { ... }. MDN says the query is evaluated against the nearest ancestor with a matching containment context, and the styles apply to descendants of that container, not to the container itself. Container query length units such as cqi (1% of the container's inline size) are available inside. MDN shows @container as Baseline since February 2023.

    Figure 2. Two kinds of question

    Media queries ask about the viewport, container queries ask about the component's spaceViewport to Media query (width); Media query to Page layout; Container to Container query (inline size); Container query to Product cardViewport: window widthViewportwindow widthMedia query: page shellMedia querypage shellPage layout: sidebar, columnsPage layoutsidebar, columnsContainer: container-typeContainercontainer-typeContainer query: componentContainerquerycomponentProduct card: layout insideProduct cardlayout insidewidthinline size

    How to read this: the top row decides where big regions go; the bottom row decides how one reusable component arranges itself in the space it was given.

    Fluid type and units. clamp(MIN, VAL, MAX) is max(MIN, min(VAL, MAX)): a size that follows the viewport between two bounds. MDN's accessibility note: when you use clamp() for text size, make the maximum a relative unit no less than twice the minimum, so that text can still scale to at least 200% on zoom (its example is clamp(1rem, 2.5vw, 2rem)). For full-height layouts, vh is the same as lvh, the large viewport; svh is the small viewport, and dvh follows the browser toolbars as they appear and disappear, but MDN warns that dynamic units are not stable and can resize content while the user scrolls. Prefer logical properties such as inline-size and the start and end alignment values, which follow the writing mode instead of physical left, right, width and height.

    Illustration 3: a failure, the container that was not marked

    The product card changes layout with a container query:

    .product-card-slot { container-type: inline-size; container-name: card; }
    
    @container card (width > 400px) {
      .product-card { grid-template-columns: 120px 1fr; }
    }

    If a developer reuses .product-card in the cart upsell panel and forgets the wrapper with container-type, the rule is evaluated against the nearest ancestor that is a matching container, which might be a page-wide wrapper far above the card. The card then lays itself out for the width of the page instead of the panel. This follows from MDN's description of which container is queried; it was not rendered here.

    A second trap follows from the unit definitions. A panel with height: 100vh uses the large viewport, the size when browser toolbars have retracted, so while they show the bottom of the panel can sit below the visible area. svh avoids that, and dvh follows the toolbars but can resize content while scrolling.

    Trade-offs

    Choice Gain Cost
    Flexbox for one-dimensional rows Simple, great alignment control No alignment across rows
    Grid with auto-fill and minmax() No breakpoints for column count Cards stretch with 1fr; cap with a max or a container if that looks wrong
    Subgrid Cross-card alignment A parent grid to manage; learn two sets of line numbers
    Media queries Right for page shell decisions Wrong for reusable components
    Container queries Components adapt to their slot Needs a container-type on an ancestor; containment has side effects
    clamp() for type Fluid sizes, no breakpoints Needs rem bounds to keep zoom working
    dvh Fits the visible area Not stable while toolbars move

    Build it

    This lesson has no lab. The CSS blocks are shown, not run. The Node snippet in Illustration 2 is a model of the auto-fill rule and needs no install; it says nothing about how any browser paints. No browser run was performed here, so no screenshots or measurements are shown.

    In practice: the product listing page

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The listing page uses a 12-column float system and five breakpoints (illustrative), each with hand-tuned card widths. The product card is also used in a recently viewed strip and a cart upsell panel, each with its own copy of the card CSS because the card's media queries assume full width. A request for "four columns on wide screens" needs changes in three places. On small phones the page scrolls sideways, and the viewport tag disables zoom.

    Starting architecture

    Figure 3. Layout decided by the viewport everywhere

    Starting architecture: every layout decision is a viewport breakpointViewport to Listing grid; Viewport to Recently viewed; Viewport to Cart upsell; Listing grid to Product card; Recently viewed to Product card; Cart upsell to Product cardViewport: 5 breakpointsViewport5 breakpointsListing grid: float columnsListing gridfloat columnsRecently viewed: card copyRecentlyviewedcard copyCart upsell: card copyCart upsellcard copyProduct card: assumes full widthProduct cardassumes fullwidth

    How to read this: the warning boxes are where the viewport is asked a question that only the slot can answer. A card in a narrow panel on a wide screen gets the wrong layout.

    Options considered

    Option What it fixes What it costs Risk
    Add more breakpoints Fixes each reported case More CSS to maintain The next slot breaks again
    Grid for the page, container queries for the card, media queries for the shell One card, any slot; no column ladder Learn containment; check support for the audience container-type forgotten on a wrapper
    Rebuild the card per slot Exact control Three card implementations Drift between them

    The decision

    Field Decision record
    Context The card's layout depends on the screen, but its width depends on its slot.
    Decision Use repeat(auto-fill, minmax(220px, 1fr)) for the listing, a container-type: inline-size wrapper and @container rules inside the card, media queries only for the sidebar and header, clamp() with rem bounds for headings, and width=device-width without user-scalable=no.
    Consequences, good One card works in every slot; column count follows width; zoom works.
    Consequences, bad Containment on the wrapper; team must learn when to use which query.
    Revisit when Analytics show old browsers in your audience, or the card needs style queries or other newer features.

    Figure 4. Target architecture

    Target architecture: slots are containers, the card responds to its slotViewport to Page shell (width); Page shell to Listing grid; Listing grid to Card slot (cell); Card slot to Product card (inline size)Viewport: shell onlyViewportshell onlyPage shell: media queryPage shellmedia queryListing grid: auto-fill minmaxListing gridauto-fill minmaxCard slot: container-typeCard slotcontainer-typeProduct card: container queryProduct cardcontainer querywidthcellinline size

    How to read this: the viewport only decides the shell. Every place that holds a card is a slot marked as a container, and the card asks its slot, not the screen, how to arrange itself.

    Rollout and verification

    1. Fix the viewport meta element first and confirm zoom works on a real phone.
    2. Replace the float grid with the auto-fill grid on one page behind a flag, and compare column counts with the model in Illustration 2.
    3. Wrap each card slot with container-type: inline-size and move the card's media queries to @container.
    4. Test reflow at 320 CSS pixels (WCAG 1.4.10 asks vertical-scrolling content to work there without two-dimensional scrolling; that equals a 1280 pixel viewport at 400% zoom) and with text zoomed to 200%.
    5. Check the strip and the upsell panel, a narrow slot on a wide screen.

    The 2 a.m. failure

    A new "frequently bought together" panel ships on the cart page. Its cards appear in the wide two-column layout inside a narrow panel and their text overflows. The slot wrapper was copied without container-type, so the card's @container card rule is matched against a farther ancestor.

    First three checks: (1) find which ancestor carries container-type and container-name: card for the broken card; (2) confirm the query's name matches; (3) compare with a working slot. Mitigation: add container-type: inline-size and the name to the new wrapper. Follow-up: a test that renders each slot and asserts the wrapper declares a container.

    Architect's notes

    • Make the slot the container. Components should not know the screen width; the place that holds them should.
    • Media queries for regions, container queries for components.
    • Prefer intrinsic sizing (fr, minmax, clamp) over fixed breakpoints.
    • Test at 320 CSS pixels and at zoom.
    • Check support for features newer than your audience's browsers. The CSS architecture lesson in this module covers organising the styles, and the rendering pipeline lesson covers what layout costs.

    Common mistakes

    • Flexbox for a layout that needs aligned rows and columns, then adding hacks.
    • Breakpoints named after devices instead of content.
    • Disabling zoom with user-scalable=no.
    • Fluid type with no rem bounds, so zoom does not scale it.
    • 100vh on mobile for something that must fit the visible area.
    • Forgetting container-type, or styling the container itself instead of its children.
    • Leaving cards and images without reserved space; see CLS and Layout Stability.

    Key takeaways

    • Flexbox is one-dimensional; grid is two-dimensional. Choose by the shape of the layout.
    • repeat(auto-fill, minmax(min, 1fr)) gives a responsive column count without breakpoints; auto-fit collapses empty tracks.
    • Subgrid lets nested items use the parent grid's tracks.
    • Media queries ask about the viewport; container queries ask about the nearest container and style its descendants.
    • clamp() with rem bounds keeps fluid type zoomable; dynamic viewport units track browser toolbars but are not stable.
    • Do not disable zoom, and check reflow at 320 CSS pixels.

    Practice exercises

    Exercise 1: Starter (30 min). Change 220 to 180 and 16 to 8 in the Illustration 2 model, predict the column counts for the five widths, then run it.

    Exercise 2: Intermediate (2 hours). Build the product grid and a card with one @container rule in an HTML file. Put the card in a wide grid cell and a narrow sidebar, and write down what you expect before you open it in a browser.

    Exercise 3: Advanced (half day). Take a page you own and remove every breakpoint you can without a visible change at 320, 768 and 1280 CSS pixels. Keep a list of the ones you could not remove and why.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments