Turning a flexbox into a grid using flex-wrap and align-content

Share this video with your friends

Social Share Links

Send Tweet

Adding flex-wrap to a flexbox container allows the items to form a grid. The content can then be aligned and distributed along the grid using justify-content and align-content.

[00:00] Adding wrapping to a long flexbox list can give you some nice grid-like features. In this example, I have seven images from Unsplash, each with a caption of the photographer.

[00:10] Let's start by setting display: flex on the main container. In this case, it's the body tag. Let's fix the width. Right now, it's set using the width property. I'm going to uncomment this flex property to keep it more flexbox friendly.

[00:22] Also, the flex-grow here is set to zero, so it doesn't get away from us. Now, we can see the list of images flow horizontally, which is fine. We don't really want it to go off the page. Let's add flex-wrap which defaults to nowrap.

[00:36] Let's set it to wrap. There is one other option. We could also set it to wrap-reverse which causes the line breaks to flow up instead of down in this case. Notice the content bunches up to the top left corner.

[00:48] If we want to spread it out a bit, we can add justify-content: space-around which we know will give us a nice space along the flex direction axis. It also affects the alignment of the orphaned item on that last row.

[01:02] That doesn't really help us with our vertical rhythm. We can add align-content. It has values that we're already familiar with -- flex-start, flex-end, center, space-between, space-around, and stretch.

[01:32] Stretch isn't going to show much because we have a fixed width and height. Align-content is only used with multi-line content. Make sure not to confuse it with align-items or align-self, as it won't do anything on single line content.