Skip to main content

Make a CSS toolbar wrap without losing a button

Updated 2 min readMarkdown

Three short buttons can fit on a desktop and overflow on a phone. A flex container lays items on a single line by default. If the items cannot shrink, the last button may end up past the edge of the toolbar. This exercise shows you how to reproduce that failure and measure what changes when wrapping is enabled.

Make a toolbar that overflows

Open the Edit HTML Online editor. Start with a blank example, then paste this markup into the HTML tab.

<div class="toolbar" role="group" aria-label="Article filters">
  <button type="button">All articles</button>
  <button type="button">Browser tutorials</button>
  <button type="button">Website performance</button>
</div>

In the CSS tab, add these styles.

body { font: 1rem system-ui; margin: 1rem; }
.toolbar { display: flex; gap: .5rem; }
.toolbar button {
  flex: 0 0 auto;
  font: inherit;
  white-space: nowrap;
  padding: .65rem .8rem;
}

Set the preview to Mobile and run the code. In my Chrome test, the preview viewport was 375 px wide. The toolbar itself had 343 px of available space, and its content needed 458 px. The exact measurements depend on the font and browser. To check your own result, compare the toolbar’s clientWidth and scrollWidth in the browser inspector. If the second value is larger, the content overflows the available width.

Allow items to wrap

Add flex-wrap: wrap to the toolbar rule.

.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: .5rem;
}

At the same width, the last button moves to a new row. In the test, the toolbar’s content width dropped to 343 px, matching the available space. The gap now applies between buttons and between rows. Switch back to Desktop and the buttons can sit on one line again, without a breakpoint.

Test the edge cases

Try a longer translated label. Flex wrapping moves whole items onto a new row. A single button that is wider than the container can still overflow. Allow its text to wrap by dropping white-space: nowrap, and cap its inline size when the design calls for it. If a label contains an unusually long unbroken word, try overflow-wrap: anywhere and check how it looks. Tab through the buttons to make sure you can see the focus indicator and that the focus order follows the reading order.

This tutorial was prepared with AI assistance and browser-tested for Edit HTML Online, the publication behind the editor used in the example.

About the author

  • Free browser-based web development tools and step-by-step examples for learning HTML, CSS and JavaScript. https://edithtmlonline.com/

No comments yet. Be the first to comment.