Auto-Fill Your CSS Grid With Max Columns and Minimum Size

26 May 2023 Balmiki Mandal 0 MERN Full Stack

Creating an Auto-Filling CSS Grid With Max Columns of a Minimum Size

One way to create an aesthetically pleasing grid layout is by adding columns of a minimum size into the mix. However, trying to manually set the number of columns can be a bit of hassle, especially when trying to achieve a responsive design. That’s why it’s useful to know how to leverage CSS to automatically fill a grid with columns of a minimum size. In this tutorial, we’ll look at the process for creating an auto-filling grid using the max-columns and minmax() properties in CSS.

Step 1: Defining the Container

The first step to creating an auto-filling grid is to create a container element that will hold the grid. This container should be given a width of 100%.

<div class="container">
</div>

.container {
    width: 100%;
}

Step 2: Setting the Max Columns and Minimum Size

Next, you’ll need to set your maximum number of columns and the minimum size of each column. This is done using the max-columns property. For example, if you want a maximum of four columns, each with a minimum width of 200px, then your code would look like this:

.container {
    max-columns:  4;
    minmax(200px, 1fr);
}

Step 3: Creating the Grid Items

Now that the container and columns are defined, the next step is to create the actual grid items. This can be done by using the inline-grid property and setting the max-columns and minmax() properties for each item. For example, if you want the first item to be 200px wide, the second item to be 300px wide, and the third and fourth items to be 400px wide, your code would look like this:

.item {
    display: inline-grid;
    max-columns: 4;
    minmax(200px, 1fr);
}

.item-1 {
    minmax(200px, 1fr);
}

.item-2 {
    minmax(300px, 1fr);
}

.item-3,
.item-4 {
    minmax(400px, 1fr);
}

Step 4: Finishing Up

Finally, you’ll need to make sure that the items are laid out properly within the grid. This can be done by adding the grid-template-areas and grid-template-columns properties to the container. For example, if you want the first two items to be in the first row and the last two items to be in the second row, your code would look like this:

.container {
    display: grid;
    grid-template-areas: 
        "item-1 item-2"
        "item-3 item-4";
    grid-template-columns: repeat(4, minmax(200px, 1fr)); 

    max-columns:  4;
    minmax(200px, 1fr);
}

And that’s it! You’ve now successfully created an auto-filling grid with maximum columns of a minimum size. By combining the max-columns, minmax(), inline-grid, grid-template-areas, and grid-template-columns properties, you’ll be able to create a beautiful, responsive grid layout without having to manually specify the number of columns.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.