How can I make columns shrink to fit content and repeat in CSS Grid layout?

Is it possible to create a CSS Grid layout that dynamically shrinks columns based on the size of the content while repeating (wrapping) cells?

Consider the following configuration:

display: grid;
grid-template-columns: repeat(auto-fit, minmax(0, 1fr));

example image

In this example, the columns adjust their width according to the content size as the screen collapses.

another illustration

This image demonstrates how one column can be narrower than the others based on content width.

The grid-template-columns: repeat() function takes two args, but is there a way to automatically compute the column width based on content?

Here is my attempt at achieving this in this CodePen.

You can also view a real-world example here, where the first column should expand to fill the content while the second column adjusts accordingly.

If you have any advice or guidance on accomplishing this using CSS Grid, please share!

Answer №1

You have the ability to create columns that repeat based on content size, but for a fixed number of columns. When using auto-fit or auto-fill, the grid will make all cells the same width.

In your scenario, it appears to be a 3x3 layout.

display: grid;
grid-template-columns: repeat(3, min-content);
*,
::after,
::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: grid;
  place-items: center;
  background-color: hsl(215, 100%, 98%);
  position: relative;
  overflow-x: hidden;
}

.container {
  background-color: lightgray;
  width: 760px;
  display: grid;
  grid-template-columns: repeat(3, min-content);
  resize: horizontal;
  overflow: hidden;
  gap: 5px;
  justify-items: center;
  align-items: center;
}

.child {
  background-color: gray;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

p {
  text-align: center;
}
<div class="container">
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/80x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/120x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/160x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/80x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/120x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/160x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/80x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/120x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/160x75" alt="" />
  </div>
</div>

A question was raised about the usage of repeat() function with minmax(). It was mentioned that while the first parameter specifies the minimal width, like 186px, the second determines how much it can expand.

display: grid;
grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
*,
::after,
::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: grid;
  place-items: center;
  background-color: hsl(215, 100%, 98%);
  position: relative;
  overflow-x: hidden;
}

.container {
  background-color: lightgray;
  width: 760px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
  resize: horizontal;
  overflow: hidden;
  gap: 5px;
  justify-items: center;
  align-items: center;
}

.child {
  background-color: gray;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

p {
  text-align: center;
}
<div class="container">
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/80x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/120x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/160x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/80x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/120x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/160x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/80x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/120x75" alt="" />
  </div>
  <div class="child">
    <p>title</p>
    <img src="https://via.placeholder.com/160x75" alt="" />
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When hovering over various div elements in HTML

I've been experimenting with some code lately, and I'm trying to change the text color of a menu element when hovering over it. I can alter the background color just fine, but for some reason, the text color remains unchanged. Can anyone offer a ...

Scroll bar for multiple selection select tag without using div element (not supported in firefox)

.selector select[multiple="multiple"] { border-radius: 0; height: 200px; margin: 0 0 0 -1px; max-width: 368px !important; padding-left: 3px; width: 368px !important; } <select id="id_included_packages_from" class="filtered" multiple="multipl ...

Ways to conceal rows within an implicit grid

In the code snippet below, CSS Grid is used to adjust the number of columns for wider containers. When dealing with narrower containers (such as uncommenting width: 80vw or resizing the example), implicit rows are added (with only two being specified in th ...

Detecting unutilized space in a collection of divs with varying sizes using JavaScript and CSS

To better understand my issue, I created a StackBlitz demo: https://stackblitz.com/edit/angular-aqmahw?file=src/app/tiles-example.css Screenshot My tiles can have four different widths (25%, 50%, 75%, 100%). The tiles must fit on only two lines, so if a ...

Arrange all absolute divs equidistant from each other

I'm struggling with positioning multiple absolute divs inside a relative container using the CSS 'left' property. I want these inner divs to be evenly spaced regardless of how many there are, without setting fixed values for each. Currently ...

A dual row navigation layout with the second row featuring equally distributed elements in a neat and organized manner

Looking to create a responsive collapsible navigation with two rows. The first row should contain the logo and language selector, while the second row should have the main links: | | | ...

The TailwindCSS breakpoints are not being recognized in the styling

I am currently working on a NextJS 14 project where I am integrating Tailwind CSS. Here is a snippet of the code I am using: <div className="text-amber-dim md:text-amber flex-1 h-screen flex items-center justify-center"> <div classNam ...

Using Jquery to toggle classes between "display block" and "display none

Hello friends, I'm in need of some help with my code. $(document).ready(function() { var circle = $('.circle'); $(".send a").click(function(e) { e.preventDefault(); $('.wrap').css('display', 'bl ...

I'm curious, what height would be most suitable for a first impression?

I'm in the process of building a website and I want to ensure that all elements are visible within the div without requiring users to scroll. However, I know that screen resolutions vary between computers. What can I do to address this issue? Is ther ...

Troubleshooting: Custom checkbox using CSS ::before does not display properly on Firefox and Edge browsers

Encountering a frustrating CSS challenge while working on a project that needs to be compatible across various browsers. Specifically, I'm having issues with custom styling for checkboxes. Despite following recommendations to use a ::before pseudo-ele ...

Which is more efficient for rendering performance: using images, CSS gradients, or box shadows with borders?

I'm curious about improving website scroll and animation performance. Which option would be better for your mobile webapp or website: Using a repeating thin image or CSS3 gradient? or Utilizing a repeating image instead of box shadow with a borde ...

Choose the element that is trapped within the div

I've hit a roadblock with this issue that I just can't seem to figure out. I was working on a practice project creating a Netflix-like webpage, and the select element in the footer containing languages is stuck and won't budge. Here's m ...

How can I adjust the scale of the Flex Grid to fit within

I'm currently working on setting up a dynamic gallery. The number of items in the gallery will vary, and I want them to adjust to fit the browser viewport. It seems like it should be a straightforward task? My current DOM structure is as follows: < ...

Special CSS rule for targeting an active state of a specific child element

My issue involves a div with the :active selector effect. Within this div, there is a smaller child div that contains some buttons. Currently, when either the parent div or one of the buttons within the child div is clicked, the :active effect is triggere ...

Stylish slanted divs achieved using Bootstrap 4

I'm currently in the process of constructing a block with 6 slanted divs using Bootstrap. Take a look at the image provided below: https://i.sstatic.net/vvg0b.png After attempting to use rows and columns, I noticed that they weren't aligning co ...

A problem with centering a popup window using the CSS transform() function

Discovered a clever technique for creating a centered popup window in an application ( http://www.w3.org/Style/Examples/007/center ). Neat and simple code implementation ( http://jsfiddle.net/babaca/6rwL0v0c/22/ ). html <div class="__holder"> & ...

Having trouble implementing responsive image with fixed aspect ratio code

I've tried several tutorials online to make this image responsive with a fixed aspect ratio, but nothing seems to work. The image is set at 900x400px and I want it to remain fully visible on smaller screens as well. Here's the codepen link < ...

How can I prevent the expansion of elements in a drop-down menu when using display:

I've been struggling to implement a drop-down feature in my menu. The issue is that when I use display: flex, hovering over the drop-down also expands all other boxes without drop-downs. Any ideas on how to fix this easily? Additionally, is there a w ...

Styling text by reducing its size with CSS

Utilizing a CSS class to truncate text in the accordion header, which includes both a URL and plain text fields that need to be displayed on the same line. Desired Output: .../abc/xyz Count:42 Current output: .../abc/xyz Count:42/ (An odd slash is ...

The issue with data targeting in Bootstrap 3 persists

header.php code <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN"> <html lang="EN"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UT ...