When should I nest flexboxes?

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;
}
7 Likes

We can use nested flexboxes when we need the contents of one of our flex items to be easily organized, sorted, spacing, and/or scaling horizontally or vertically.

Imagine a hypothetical layout where we have a flex container () with three flex items (

), where the last flex item contains a few buttons that we want to easily arrange and space. In this situation, we’ll use a nested flexbox where the third flex item is also a flex container:

<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:

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

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

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