This video is available to students only

The Grid Component

Building an inherently responsive grid of items has been reduced down into a single line of CSS. In this lesson, you will learn how to build the Grid primitive that easily lets us achieve this layout.

In the last lesson, we made a grid to lay our elements out on. In this lesson, we are making a responsive grid of elements.

The problem: the Contact Grid List#

In this lesson, we are going to build out the following widget:

Contact list mockup

Like always, we need consistent gutters between elements. However, this time we need a fluid grid with column tracks at least 24rems wide but which can be wider if space is available.

The solution#

As always, let's start with our basic markup, and you can follow along with this starter at codesandbox.io:

Which looks like this:

Contact list step 0

Given the requirement that we need to fit in as many cards per row as we can, while maintaining a minimum width, we can't use our Columns primitive. Luckily we can adapt the Columns primitive slightly to make our new primitive:

Just like in the Columns primitive, we are using the repeat function. However, instead of a number, we are using the keyword auto-fit. Using auto-fit allows us to defer to the browser how many column tracks to use based on the quantity and size constraints.

This brings us to the size value. Instead of simply using 1fr, like in the Columns primitive, we use the minmax function. This function allows us to set a lower and upper bound without specifying the value itself, by passing in the lower bounds number, followed by the upper bounds number: minmax(LOWER, UPPER). For example, if you wanted a value that was no less than 100px and no larger than 300px, then you would write minmax(100px, 300px). The minmax function is useful when you don't care what the value is, just as long as the value is no less than the lower bounds number and no higher than the higher bounds number.

In the above code, we have a lower bounds value of 24rems, which means each column track cannot be smaller than 24rems wide. For the upper-bound we are using 1fr, which we learned in the last lesson means one fraction of available space. This will let each track take up 1fr of available space or in other words, each column track will grow equally to take up all available space. We could put 2fr or 100fr and it would work the same. This is because, as we learned when making the Split, fr units work in ratios. To create a 1/4 fractional split, we used 1fr 3fr. Effectively, the available space is divided into four parts and one part goes to the first track and the remaining three goes into the second track. In the code above, each track will have the same upper-bound fractional value, which means they will all grow equally.

To use the Grid primitive, it looks like this:

 

This page is a preview of Composing Layouts in React

Start a new discussion. All notification go to the author.