CSS

Create Responsive Grid Layouts with auto-fit and minmax

Build highly flexible and responsive CSS Grid layouts for image galleries or product cards that automatically adjust column count based on viewport size.

/* HTML Structure Example: */
/*
<div class="responsive-grid-container">
  <div class="grid-card">Card 1</div>
  <div class="grid-card">Card 2</div>
  <div class="grid-card">Card 3</div>
  <div class="grid-card">Card 4</div>
  <div class="grid-card">Card 5</div>
  <div class="grid-card">Card 6</div>
</div>
*/

.responsive-grid-container {
  display: grid;
  /* Defines responsive columns: auto-fit creates as many columns as fit
     each with a minimum width of 250px and a maximum of 1fr (equal fraction) */
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem; /* Gap between grid items */
  padding: 1rem;
  background-color: #f8f9fa;
}

.grid-card {
  background-color: #6f42c1;
  color: white;
  padding: 2rem 1rem;
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-size: 1.2rem;
}
How it works: This snippet demonstrates how to create a dynamic and responsive grid layout that automatically adjusts the number of columns based on the available space. The key is `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))`. `auto-fit` tells the grid to create as many columns as can fit without overflowing, and `minmax(250px, 1fr)` ensures each column is at least 250px wide but will grow up to an equal fraction of the remaining space, making it perfect for card layouts or image galleries that need to adapt to various screen sizes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs