Flex-wrap

In this lesson, we will create a Flexbox-based grid with multiple rows or columns using flex-wrap. We will learn why wrapping is beneficial when creating a list of blog posts or a list of images.

Challenges with creating multiline grid structure

When creating a gallery of images or a landing page displaying thumbnails of blog posts, it is a natural phenomenon that we prefer styling each image or post in a container, regardless of whether they are displayed in one line or multiple lines.

The following markup is not intuitive:

<div class="container">
  <div class="row">
    <div class="blogpost">Post 1</div>
    <div class="blogpost">Post 2</div>    
    <div class="blogpost">Post 3</div>
  </div>
  <div class="row">
    <div class="blogpost">Post 4</div>
    <div class="blogpost">Post 5</div>    
    <div class="blogpost">Post 6</div>
  </div>
</div>

The problem with the above markup is that we hardcode the presentation. Using this layout, we have to display all three blogposts in one row. This is not too good when creating responsive layouts.

Therefore, the need arises to create layouts like this:

<div class="container">
  <div class="blogpost">Post 1</div>
  <div class="blogpost">Post 2</div>    
  <div class="blogpost">Post 3</div>
  <div class="blogpost">Post 4</div>
  <div class="blogpost">Post 5</div>    
  <div class="blogpost">Post 6</div>
</div>

Whether these posts are displayed in one column or three-columns, it is a decision we have to take in our CSS files.

Let’s provide some basic styles for our container and our post:

.container {
  display: flex;
  justify-content: space-evenly;
  width: 800px;
}

.blogpost {
  width: 225px;
  height: 150px;
  box-sizing: border-box;
  border: 1px solid black;
  background-color: lightgrey;
}

We will also add a black ruler element to measure how wide 800px is.

After displaying these elements, we’ll see the following result:

Get hands-on with 1200+ tech skills courses.