When should I nest flexboxes?


#1

Question

When should I nest flexboxes?

Answer

We can use nested flexboxes when we require the content of one of our flex items to be easily aligned, ordered, spaced and/or scaled in a horizontal or vertical direction.

Imagine a hypothetical layout where we have a flex container (<section> element) with three flex items (<div> elements), where the last flex item contains some buttons that we want to align and space easily. In this situation we’ll want to use a nested flexbox where our third flex item is also a flex container:
HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>My Site - Flexbox</title>
</head>
<body>
<section>
  <div></div>
  <div></div>
  <div class="with-content">
    <button>btn 1</button>
    <button>btn 2</button>
    <button>btn 3</button>
  </div>
</section>
</body>
</html>

CSS:

section {
  display: flex;
  border: 1px solid black;
  justify-content: space-between;
  flex-wrap: wrap;
}

div {
  width: 300px;
  height: 200px;
  border: 1px solid red;
}

.with-content {
  display: flex; /*will make our third flex item, within our `<section>` element, a flex container*/
  align-items: center;
  justify-content: space-around;
  flex-wrap: wrap;
}