How can I get an even number of elements on each row whilst using flex-wrap?

Whilst doing the Flex-box lesson, I noticed as I shrunk the screen size, the 5 elements split into two rows; the first with 4 elements, and the second with just 1. I was wondering if it’s possible to wrap elements using flex-box in a more symmetrical way.

Let’s say that we have 6 elements that fit horizontally into a container, but then I reduce the screen size. As it stands the elements would fall into two rows like below:

image

However, my aim is to get them to split into two equal rows of three, even though there is sufficient room for four elements next to each other. If I then reduce the screen size further, I’d like it to split into three rows of two elements.

image

(Just to add, if we had an odd number of elements, splitting into almost equal rows would be fine. E.g. 7 elements splitting into a row of 4 and a row of 3.)

I guess I could use media queries to change the width of the container as the screen size reduces, however I was hoping for a more responsive solution that works regardless of the size or number of elements.

I hope that all made sense…

The code below is taken from the flex-wrap lesson and I just removed some elements to avoid repetition.:

<html>

<head>
  <title>Wrap</title>
  <link href="style.css" type="text/css" rel="stylesheet" />
  <link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet">
</head>

<body>
  <h1>Flex-Wrap: Wrap</h1>
  <div class="container" id="wrap">
    <div class="box">
      <h3>1</h3>
    </div>
    <div class="box">
      <h3>2</h3>
    </div>
    <div class="box">
      <h3>3</h3>
    </div>
    <div class="box">
      <h3>4</h3>
    </div>
    <div class="box">
      <h3>5</h3>
    </div>
    <div class="box">
      <h3>6</h3>
    </div>
  </div>
</body>

</html>
body {
  font-family: 'Roboto Mono', monospace;
}

h1 {
  font-size: 18px;
}

h1,
h3 {
  text-align: center;
}

.container {
  background-color: dodgerblue;
  display: flex;
  align-items: center;
  min-height: 125px;
  justify-content: space-around;
}

.box {
  background-color: whitesmoke;
  border: 1px solid white;
  width: 100px;
  height: 100px;
}

#wrap {
  flex-wrap: wrap;
}

Thanks for any help you can give!

FAQ: Flexbox - flex-wrap