No Time Dad

A blog about web development written by a busy dad

Flexbox Flex-Wrap Use Case

My favorite use case for Flexbox flex-wrap is creating a responsive grid. In fact, it’s so good at this that Bootstrap uses it under the hood for their grid system. Which always makes me chuckle since it’s called “grid” but it no longer uses display grid.

The flex-wrap property determines if the items in a flexbox container should be displayed on one line or wrapped onto multiple lines as the screen size changes.

With flex-wrap

flex-wrap-squares2

main {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}
Without flex-wrap

no-flex-wrap

main {
  display: flex;
  gap: 1rem;
}
Full code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Flexbox flex-wrap Example</title>
</head>
<style>
  main {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
  }

  main > div {
    width: 150px;
    height: 150px;
    background-color: cornflowerblue;
  }
</style>
<body>
  <main>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </main>
</body>
</html>

Using flex-wrap makes responsive design easy. Assuming your design is simple. If you needed more fine grained control over the layout, then you might want a different solution. Something like display grid might be better. But a quick responsive grid or even a responsive nav header might be good candidates for using flexbox flex-wrap.