Choose Between Grid or Flexbox for CSS Layout

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 7 months ago

Learn the fundamental difference between CSS grid and flexbox layout, and create utility classes for each display value. Then begin to apply and expand these concepts to style the landing page navigation.

Instructor: [0:00] Grid and flex are both values of the display CSS property. Let's begin by creating the utility classes for display-flex and display-grid.

[0:11] Right now, this is semantically marked up. We want to treat both the app title and the nav items as one layout unit. We'll wrap them in additional div with the class navbar.

[0:24] The first step in choosing between grid or flexbox is considering which axis child element should align on. Both are capable of aligning on either the X, or horizontal axis, or the Y, or vertical axis.

[0:40] Let's start by adding the display-flex class. The default alignment is on the X axis, which is already a step closer to our desired result. We'll swap to the display-grid class. Due to grid's default of aligning on the Y axis, the visual effect now appears no different than normal block layout. Let's revert to display-flex.

[1:06] Before we work on the alignment of the nav items, let's remove the default list styling with a quick utility class. Next, we need to align the nav links. Based on our current progress, it may seem that flexbox is the correct choice, which we can try.

[1:23] We encounter an issue with flexbox, which is that the default behavior causes the nav list items to run into each other. Let's switch to display-grid. We'll add a modifier for this class. To switch the default axis using the property grid-auto-flow with the value column. Then add this modifier class as well.

[1:50] Now on our base display class, we'll add the unique to grid property grid-gap and set it to twice our themes to find unit value. Upon save, we now see how the grid-gap has created space between the nav list items.

[2:07] However, we'd prefer that the title align to the left and the nav links align to the right. For this, let's begin our navbar class and define justify-content, space-between, which will assign extra horizontal space between the flex children.

[2:26] We'll also add a touch of padding to the navbar. This view is looking pretty good, but if we resize the viewport, the title and the nav links crash. Another flex-only property is the concept of wrapping which allows flex children to drop below one another when there isn't enough horizontal space, such as on smaller viewports.

[2:49] Let's extent the display-flex class to add a modifier to define flex-wrap wrap, and add this modifier to our layout. Now when we resize the viewport, the nav links drop below the title. Our navbar styles are complete.