CSS Flexbox Explained for Beginners: 10 Layout Patterns You Will Actually Use

In short: CSS flexbox for beginners comes down to one idea. You put display: flex on a parent element, and its direct children line up in a row or a column that you steer with a handful of properties. Learn the two axes first, then the ten layout patterns below, and you’ll cover most of what everyday websites ask of flexbox. CSS Grid takes over when you need rows and columns at the same time.

Flexbox is short for the CSS Flexible Box Layout module. It’s a one-dimensional layout model, which means it arranges items along one line at a time, in a row or column, and decides how the leftover space is shared. That’s why it fits navigation bars, button groups, card rows and centered content so well. This guide teaches it the way you’ll use it: by building recognizable components with annotated code, not by memorizing property definitions.

How flexbox works: one container, its children and two axes

A flex layout always has two layers. The flex container is the parent container: to create a flex container, you set an element’s display property to flex. The flex items are its direct children, and only them.

A grandchild doesn’t become a flex item unless its own parent is also a flex container. Many “flexbox isn’t working” moments start right there, with the property set on the wrong element.

Everything else is measured along two axes. The main axis follows flex-direction, which is a row by default. The cross axis runs perpendicular to it. (via https://blog.ljwebmanagement.com)

With flex-direction: row, the main axis is horizontal and the cross axis vertical. Switch to column and the items stack from top to bottom, or from bottom to top with column-reverse. The axes swap too. That’s why a property that centered things horizontally suddenly centers them vertically.

Flexbox also speaks of start and end rather than left and right. In English, a row starts on the left; in Arabic, which reads right to left, it starts on the right. This logical approach to direction feels odd for a day or two, then pays off when you move on to the grid layout module, which follows the same logic.

What happens the moment you write display: flex

According to MDN (Mozilla Developer Network, now MDN Web Docs) and its guide to the basic concepts of flexbox, a new flex container starts with these initial values:

  • items sit in a single row (flex-direction: row) and start from the start edge of the main axis;
  • they don’t grow (flex-grow: 0) but they can shrink (flex-shrink: 1);
  • they stretch to fill the cross axis (align-items: stretch);
  • their starting size comes from their width, or from their content if no width is set (flex-basis: auto);
  • they don’t wrap (flex-wrap: nowrap), so too many items overflow the container.

That stretch default explains a common surprise: put a short card next to a tall one and both end up the same height. You can declare display: flex or inline-flex: choose the second when the container itself should sit inline, like a badge or an icon-and-label button inside a line of text.

css layout code

The container properties: direction, wrapping, alignment and gap

Most of the layout work happens on the parent. Here are the properties you’ll set on a flex container, what they control and their default value.

Property What it controls Values you’ll use most Default
flex-direction Direction of the main axis row, column, row-reverse, column-reverse row
flex-wrap Whether items may move onto new lines nowrap, wrap nowrap
flex-flow Shorthand for direction and wrap row wrap, column row nowrap
justify-content Distribution along the main axis flex-start, center, flex-end, space-between, space-around, space-evenly flex-start
align-items Alignment along the cross axis stretch, center, flex-start, flex-end, baseline stretch
align-content Spacing between lines once items wrap flex-start, center, space-between, stretch normal (behaves as stretch)
gap Space between items 1rem, 16px 24px 0

The three spacing values of justify-content are easy to mix up. The value space-between puts the first item at the start line and the last item at the end line, with equal gaps in between. With space-around, every item gets equal space on both sides, so the outer edges get half the gap you see between two items. Finally, space-evenly makes every gap equal, edges included.

The memory trick that helps most: justify works along the main axis, align works along the cross axis. “Content” means the group is distributed as a whole, while “items” means each item is positioned on its own. So justify-content spreads the group along the row, and align-items lines up each item vertically within that row.

Use the gap property for spacing rather than margins. It only adds space between items, never on the outer edges, so you don’t need a :last-child rule to remove a stray margin. Keep in mind that align-content only works when items sit on multiple lines: as long as flex-wrap stays at nowrap, it has no visible effect. bytegrad.com walks through the specifics.

The item properties: flex-grow, flex-shrink, flex-basis and the flex shorthand

Children control their own size through three properties, and all three decide how the available space is distributed. MDN gives a clear example. Three items of 100 pixels in a 500-pixel container use 300 pixels, which leaves 200 pixels of available space. By default, flexbox leaves that space after the last item.

  • flex-basis is the starting size before any growing or shrinking. With the default auto, the browser uses the item’s width, or its content size if no width is set.
  • flex-grow says how much of the leftover space an item takes. Give all three items flex-grow: 1 and they grow to fill the container, sharing the 200 pixels equally. Give the first one 2 and the others 1, and the space is split into four parts, two of them for the first item.
  • flex-shrink says how much an item gives up when space runs short. The default of 1 lets every item shrink, while 0 prevents it.

You’ll rarely write the three separately. The flex shorthand property sets flex-grow, flex-shrink and flex-basis in one line, and the CSS specification defines flex: 1 as a grow of 1, a shrink of 1 and a basis of 0%. That zero basis is why flex: 1 items end up equal in width even when their content differs. Write flex: 2 on one item and flex: 1 on another, and the first one takes two thirds of the space.

Two other keywords cover most remaining cases. The value flex: none (0 0 auto) freezes an item at its natural size, which suits a logo or an icon. With flex: auto (1 1 auto), an item can grow and shrink from its natural size instead of from zero.

Two more properties act on individual items. The first, align-self, overrides align-items for one child without affecting its siblings, for example to pin a single item to the bottom of the row. The second, order, changes the visual position of an item without touching the HTML. It can even put a group in reverse order, and the accessibility section below explains why it needs care. freecodecamp.org has covered this at length.

css layout code

CSS flexbox for beginners: 10 layout patterns, starting with the basics

Each pattern shows the minimum CSS, with comments on the lines that do the work. The class names are only examples; what matters is the parent-child relationship.

1. Center anything horizontally and vertically

.hero {
  display: flex;
  justify-content: center; /* main axis: horizontal */
  align-items: center;     /* cross axis: vertical */
  min-height: 100vh;       /* the container needs a height */
}

Vertical centering only works if the container is taller than its content. Without min-height, the box is exactly as tall as the div inside it, so there’s nothing to center in. The unit 100vh means 100% of the viewport height, the visible part of the browser window.

2. Navigation bar with the logo on the left

.navbar { display: flex; align-items: center; gap: 1.5rem; }
.navbar .logo { margin-right: auto; } /* pushes the links to the right */

An auto margin on a flex item absorbs all the free space on that side. It’s the cleanest way to split a navbar into a left group and a right group without extra wrapper elements. Setting justify-content: space-between also works when there are exactly two children, a logo and a single list of links.

3. Equal-width columns

.columns { display: flex; gap: 2rem; }
.columns > * { flex: 1; } /* same share for every column */

Because flex: 1 starts from a zero basis, three columns stay equal even if one holds a long paragraph. Remove it and each column sizes itself to its content.

4. A row of cards that wraps on small screens

.cards { display: flex; flex-wrap: wrap; gap: 1.5rem; }
.card { flex: 1 1 250px; } /* grow, shrink, start at 250px */

Each card wants to be 250 pixels wide, grows to fill the row and drops to the next line when it no longer fits. You get a responsive layout without a single media query. The catch: a lone card on the last line stretches across the whole width. If the last row must keep the same column widths, that’s a job for Grid.

5. Sticky footer on a short page

body { display: flex; flex-direction: column; min-height: 100vh; margin: 0; }
main { flex: 1; } /* main absorbs the extra height */

On a page with little content, the footer would normally sit halfway up the screen. Here the body becomes a column, and main takes all the leftover height, which pushes the footer to the bottom of the window. On long pages nothing changes, because the footer simply follows the content.

Patterns 6 to 10: components you’ll build every week

6. Media object: an image next to text

.media { display: flex; align-items: flex-start; gap: 1rem; }
.media img { flex: none; width: 64px; } /* never squeezed */
.media .body { flex: 1; min-width: 0; }

This is the comment, testimonial or author-box layout. Here flex: none keeps the avatar at 64 pixels however long the text gets, and align-items: flex-start stops the image from stretching to the height of the text.

7. Input and button on one line

.search { display: flex; gap: 0.5rem; }
.search input { flex: 1; min-width: 0; } /* takes the remaining width */

The field grows while the button keeps its natural size. The min-width: 0 line matters here, since some inputs refuse to shrink below their default width and push the button out of a narrow container.

8. Sidebar and main content side by side

.layout { display: flex; gap: 2rem; }
.layout aside { flex: 0 0 260px; } /* fixed width: no grow, no shrink */
.layout main { flex: 1; min-width: 0; }

Beginners often get stuck on this one, with main and aside stacked when they should sit side by side. The fix is to make their shared parent the flex container and keep the default row direction. On phones, switch .layout to flex-direction: column in a media query so the sidebar moves under the content.

9. Hero section with stacked content

.hero-content {
  display: flex;
  flex-direction: column;
  align-items: center;   /* now centers horizontally */
  text-align: center;
  gap: 1rem;
}

Once the direction is column, the axes swap. align-items: center now centers horizontally, and justify-content would act vertically. In our view, this swap is behind most “why did my alignment change?” moments. The same instinct shows in the work of a team that handles this well.

10. Equal-height cards with buttons aligned at the bottom

.card { display: flex; flex-direction: column; }
.card .button { margin-top: auto; } /* pushed to the bottom of the card */

Cards in a flex row already share the same height, thanks to align-items: stretch. Making each card a column flex container too, a nested flex container, lets the auto margin push the button to the bottom. The buttons then line up even when the descriptions have different lengths.

css layout code

Making flexbox layouts responsive and accessible

Flexbox handles a lot of responsiveness on its own, adjusting items within the container through wrapping and flex-basis, as pattern 4 shows. Media queries take over when the structure itself must change, for example turning a row into a column below a given screen size:

@media (max-width: 700px) {
  .layout { flex-direction: column; }
}

That 700px is only an example breakpoint, so pick the width where your own content starts to look cramped. A useful check comes from the Web Content Accessibility Guidelines (WCAG). Success criterion 1.4.10 Reflow, at Level AA, asks that content stay usable at a width of 320 CSS pixels without scrolling in two directions.

The order property and the -reverse directions only change what’s displayed, not the source order. Screen readers and the Tab key still follow the HTML.

WCAG 2.2 criteria 1.3.2 Meaningful Sequence and 2.4.3 Focus Order both apply here. If the visual order matters for understanding, change the HTML rather than reordering with CSS. Keep order for cosmetic tweaks such as moving an image above a heading on mobile.

Navigation links laid out with flexbox should also stay easy to tap. WCAG 2.2 sets a minimum target size of 24 by 24 CSS pixels under criterion 2.5.8 (Level AA), with some exceptions. So give the links in a compact flex navbar enough padding, not just a gap between them.

Flexbox or CSS Grid? A decision table

Flexbox is still used everywhere, and it isn’t competing with Grid. Flexbox is one-dimensional: it lays items out along one row or one column and lets their content drive the sizing. Grid is two-dimensional: you define rows and columns first, then place items into them. Most real pages use both, Grid for the page skeleton and flexbox for the components inside it.

Which one is easier? For a beginner, flexbox, because two or three properties already give a useful result. Grid becomes the easier option as soon as you’d otherwise nest several flex containers to fake columns.

If you’re building Use Avoid
A navbar, toolbar or button group Flexbox with gap and an auto margin Floats, or a grid with fixed columns
Centered content (hero, modal, empty state) Flexbox, or Grid with place-items: center Absolute positioning with negative margins
A row of cards whose number varies Flexbox with flex-wrap Fixed percentage widths
A gallery where every row must align Grid with repeat(auto-fill, minmax(200px, 1fr)) Flexbox wrapping (the last row stretches)
A page with header, sidebar, main and footer Grid for the skeleton, flexbox inside each area Three levels of nested flex containers
A form row with a field and a button Flexbox with flex: 1 on the field Tables used for layout

For a gallery-style site, we’d draw the line this way: the thumbnail grid is Grid, while the filter bar, the card footer and the author line are flexbox.

css layout code

Five beginner mistakes and how to fix them

  1. Nothing happens after display: flex. The property sits on the items themselves or on a distant ancestor, but only direct children become flex items. Put it on the immediate parent of the elements you want to arrange.
  2. align-items: center doesn’t center vertically. The container is only as tall as its content, so there’s no free space on the cross axis. Give it a height or min-height.
  3. An item ignores the width you gave it. In a flex row, width acts as a starting suggestion, and the default flex-shrink: 1 squeezes the item when space runs short. Use flex-shrink: 0 or flex: none on items that must keep their size.
  4. Long text, a URL or a code block overflows its item. The CSS specification gives flex items an automatic minimum size (min-width: auto), so they won’t shrink below their content’s minimum width. Add min-width: 0 to the item; it’s also needed for text-overflow: ellipsis to work inside a flex child.
  5. You try every combination of justify and align values until one works. The real problem is not knowing which axis is the main one. Before touching alignment, say the direction out loud, as in “row, so justify is horizontal”, then change one value at a time.

How to practice and debug flexbox

Learn the properties in order of usefulness. Start with display: flex, flex-direction, justify-content, align-items and gap, which on their own cover patterns 1, 2 and 9. Add flex-wrap and the flex shorthand next. Leave align-content, order, fine-tuned shrink values and the reverse directions for the day a real layout needs them.

Your browser’s developer tools show flex layouts directly. In Chrome DevTools, the Elements panel puts a “flex” badge next to every flex container, and clicking it draws an overlay of the container and its items. A small flexbox editor next to the display: flex declaration lets you click through the justify-content and align-items values. Firefox offers a similar Flexbox Inspector in its Layout panel.

For practice, Flexbox Froggy is a free browser game where you move frogs onto lily pads with justify-content, align-items and flex-direction. After that, rebuild three components from a site you like, such as a navbar, a card and a footer, without looking at its code. That’s usually where the properties finally stick.

Flexbox checklist for your next layout

  1. Identify the parent and its direct children.
  2. Set display: flex on the parent.
  3. Choose the direction: row (default) or column.
  4. Distribute items along the main axis with justify-content.
  5. Align them on the cross axis with align-items, after giving the container a height if you need vertical centering.
  6. Space items with gap, not margins.
  7. Add flex-wrap: wrap if the items may not fit on one line.
  8. Size items with the flex shorthand: 1, none or 1 1 250px.
  9. Add min-width: 0 to items holding long text or form fields.
  10. Check the Tab order if you used order or a reverse direction.
  11. Test the layout at 320 pixels wide, with the flex overlay switched on.

Pick one pattern from this guide, the navbar or the wrapping card row, and build it from an empty file today. Change one property at a time and see what happens. Once it works without copying, the other nine come quickly, and that’s the real goal of CSS flexbox for beginners: reading a layout instead of guessing at it.

As a next step, keep the habit going: when a layout in our gallery catches your eye, open DevTools, find its flex badges and read how it was built.

Frequently asked questions

Do I still need -webkit- prefixes for flexbox?

Not for current browsers, which all support the standard, unprefixed properties. If a project really has to support very old browsers, a build tool such as Autoprefixer can add the prefixes for you. There’s no reason to write them by hand.

Does gap work with flexbox in every browser?

Yes in current browsers. MDN’s compatibility data lists support for gap in flex layouts since Chrome 84, Firefox 63 and Safari 14.1. Only add fallback margins if your audience still uses older versions.

What’s the difference between flex-basis and width?

In a flex row, flex-basis takes priority over width for the item’s starting size, unless it’s left at auto. In a column, it replaces height instead, because it always follows the main axis. Many developers simply use the flex shorthand and set width only on items that shouldn’t flex.

Do Bootstrap and Tailwind use flexbox?

Yes. Bootstrap’s grid system has been built on flexbox since version 4, and Tailwind’s flex, justify-* and items-* classes map directly to flexbox properties. Knowing the plain CSS makes those class names much easier to read and debug.

How long does it take to learn flexbox?

In our view, a few evenings of building real components are enough for the basics covered here. The finer points, like shrinking behavior and minimum sizes, come with practice on actual projects rather than from extra reading.