Reducing Risk of Layout Overflow

Customize flex-basis and flex-grow for precise control over wrapping behavior, which is crucial for responsive layouts.

Flexbox excels as a layout tool in reducing the risk of overflow. Unlike grid items, flex items of independently variable widths can be wrapped onto new rows as necessary. The ability for content to re-arrange itself upon collision is a critical tool for building responsively without media queries.

While the grid layout we explored did technically wrap, there isn't an explicit wrapping property for the grid. We achieved wrapping thanks to the use of auto-fit ( auto-fill would also be an option). With more defined grid tracks, such as grid-template-columns: 100px 300ch 1fr, we need to resort to media or container queries to change the grid layout. Otherwise, we may experience content overflow once the container or viewport is too narrow for the defined columns.

Using flex-wrap

In flexbox, we can easily enable wrapping behavior with flex-wrap: wrap.

Note: The default flexbox wrapping behavior is flex-wrap: none, so we do need to explicitly opt in when our layout would benefit from wrapping.

The images below show some basic product cards where we want the headline and price to align horizontally when there’s room. Initially, they’re using display:flex, but with the default value set, which doesn’t cause wrapping. The narrow card headline is quite squeezed and is at risk of overflow, depending on the content and container.

Get hands-on with 1400+ tech skills courses.