Define Size Range with the minmax() CSS Function to Create Responsive Grid Items

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

The minmax() CSS function defines a size range greater than or equal to min and less than or equal to max.

Using the minmax() function, we can specify the width of our items and ensure that they remain between 200px and 1fr (the remaining space available). As the viewport is resized, the absolute value will change, but always within these two limits.

With auto-fit, the number of columns is defined automatically, ensuring a responsive layout.

Instructor: [0:00] While we like that these grids are responsive and stretched to fit the screen size, we also want some more control over the minimum and maximum width or height of these grid items as the screen size changes. To accomplish this, we can utilize the minmax() function or backwards 5 columns all at 1fr each and width in the portfolio class.

[0:19] We made this happen using the repeat function. We can embed the minmax function into the repeat function. We replace the width 1fr with minmax. Let's say, minimum was 200px for the width and maximum of 1fr. The minimum widths for these portfolio items are now set to stone at 200px and the maximum is 1fr.

[0:40] However, as a screen is smaller, we see that a problem arises. Because we set the minimum width to be 200px, and we set the number of columns to 5, this layout is no longer responsive. When the display becomes smaller, the content bleeds off the page, but there's an elegant fix to this, and that's auto-fit.

[0:58] Replace 5 columns with auto-fit. Not only does it follow the minimum of 200px and maximum of 1fr width rule that we asked for, but as the screen size gets bigger, it shuffles around the items for you automatically, increasing the number of columns. When the display becomes smaller, it decreases the number of columns to make it mobile-friendly.