Combine "repeat" with "auto-fit" and fixed width column in a single "grid-template-columns"

Viewed 579

I have a column of a defined size (let's say 50px), then an undetermined number of columns that should divide the available space among themselves, and finally another 50px column.

I know this could be achieved if I knew the total number of columns beforehand:

body > div {
  grid-template-columns: 50px repeat(3, 1fr) 50px;
  display: grid; grid-gap: 1rem; background: beige; width: 80%; padding: 1rem;
}
div div { background: IndianRed; min-height: 5rem;}
<div><div></div><div></div><div></div><div></div><div></div></div>

I also know I can do a fixed sized column + n columns this way:

body > div {
  grid-template-columns: 50px repeat(auto-fit, minmax(1px, 1fr));
  display: grid; grid-gap: 1rem; background: beige; width: 80%; padding: 1rem;
}
div div { background: IndianRed; min-height: 5rem;}
<div><div></div><div></div><div></div><div></div><div></div></div>

But the specific case doesn't work as it could this way. Instead, I'm left with an empty column at the end:

body > div {
  grid-template-columns: 50px repeat(auto-fit, minmax(1px, 1fr)) 50px;
  display: grid; grid-gap: 1rem; background: beige; width: 80%; padding: 1rem;
}
div div { background: IndianRed; min-height: 5rem;}
<div><div></div><div></div><div></div><div></div><div></div></div>

Is the thing I'm trying to do achievable with grid?

1 Answers

Remove the last column from the grid template. The column template would now look like this:

grid-template-columns: 50px repeat(auto-fit, minmax(1px, 1fr));

Then add this:

div div:last-child {
     grid-column: -1;
     width: 50px;
}

That should work!

Related