DEV Community

Cover image for A Must save CSS grid Technique ! (with code)

Posted on

A Must save CSS grid Technique ! (with code)

Grids are everywhere, you encounter them everywhere from browsing the images on Google to looking at the latest movies and shows on OTT platforms, but sometimes grid is difficult to implement with only CSS. In this article let's look at my go to code snippet for grid implementation.

The CSS properties repeat(auto-fit, minmax(240px, 1fr)) are used to create a responsive grid layout without using media queries. Let's break down each part of this property:

  • The minmax() function is a built-in CSS grid function used to set a range of width In this case, the minimum value is 240px, and the maximum value is 1fr.
  • The auto-fit keyword is used to automatically place grid items, filling the available space. This property helps create a responsive layout without using media queries
  • The repeat() function is used to define a pattern of grid columns or rows.

Look at this example:

Image description

And when the display size changes,

Image description

Code for the Example:

<div class="container">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
  <div>Item 4</div>
  <div>Item 5</div>
  <div>Item 6</div>
  <div>Item 7</div>
  <div>Item 8</div>
  <div>Item 9</div>
  <div>Item 10</div>
  <div>Item 11</div>
  <div>Item 12</div>
  <div>Item 13</div>

Enter fullscreen mode Exit fullscreen mode


.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  grid-gap: 1rem;


.container > div{
  background: cyan;
  padding: 50px;
  border-style: solid;  
  border-width: 1px;  

Enter fullscreen mode Exit fullscreen mode

Also by default the root font size is 16px, so we can convert the 240px to 15rem. So in this example, the grid will automatically adjust the number of columns based on the available space, ensuring that each column is at least 240px (or 15rem) wide and distributing the remaining space equally among the columns.

grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));

Top comments (3)

ekqt profile image
Hector Sosa

Grid is an amazing skill to master in your CSS toolkit. Framing your screenshots might help making your content stand out! We've built a simple OSS tool to help with this. Check it out and let us know what you think! I'd appreciate giving it a star on GitHub if you find it helpful! Cheers!

jeetvora331 profile image

Nice Tool! starred the repo!

ekqt profile image
Hector Sosa

Huge thanks!