Don P
Don P

Reputation: 63637

CSS grid with fixed column size that adds extra columns to fill width of container

I have a grid that varies in width and number of results.

Each cell in the grid is 200x200 px.

As the grid expands, I want the column width to remain fixed and for new columns to be added in. You could imagine the grid initially having 3 columns, and when the user expands the window, a fourth column is added in to use the new whitespace.

This grid is rendering a set of search results.

  1. So I need to be able to vary the number of rows depending on number of results.
  2. I need to be able to have the columns fill up the horizontal space dynamically.
  3. I need results to first fill up each row before moving to the next row.

Here is what I've been trying, but it is not currently working as it only renders a single column (CSS in JS, but it's just CSS):

  ResultsGrid: {
    display: grid,
    gridAutoRows: 280px,
    gridAutoColumns: 280px,
    gap: 20px,
    gridAutoFlow: row-dense,
  }

  Result: {
    border: 1px solid #EAEAEA,
  }

Desired Result

enter image description here

Upvotes: 0

Views: 1690

Answers (2)

Soufiane Boutahlil
Soufiane Boutahlil

Reputation: 2604

I faced the same problem before, here is what you need:

ResultsGrid {
  display: grid;
  gridTemplateColumns: repeat(auto-fill, 200px);
  gridAutoRows: 10rem;
  gap: 20px;
}

Upvotes: 1

Yash Verma
Yash Verma

Reputation: 272

Here's my implementation:

The auto-fit argument with repeat CSS function

.grid-item {
  border: 2px solid red;
  background: orange;
  color: red;
  padding: 10px;
  border-radius: 8px;
}

.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, 200px);
  grid-auto-rows: 200px;
  gap: 6px;
}
<div class="wrapper">
  <div class="grid-item">html</div>
  <div class="grid-item">html</div>
  <div class="grid-item">html</div>
  <div class="grid-item">html</div>
  <div class="grid-item">html</div>
  <div class="grid-item">html</div>
</div>

Upvotes: 1

Related Questions