CSS grid with auto-fill: a card does not grow when it can

53 Views Asked by At

Several cards with min/max width have to be placed in a single row. They have to fill it if possible.

I tried using 2 rules:

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

and

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

Everything works fine if there are many cards. The issue is when they are too few to fill in the row.

With auto-fill the card does not grow to its maximum width when there's enough space. There's a strange jumping.

With auto-fit it grows, but then it grows further, or - if the card max width is set - the gap starts growing.

.container {
  padding: 24px 8px 8px 8px;
  margin: 8px 0;
  border: 1px solid #000;
  display: grid;
  gap: 8px;
  height: 30px;
  overflow: hidden;
  position: relative;
}

.fill {
  grid-template-columns: repeat(auto-fill, minmax(50px, 1fr));
}

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

.flex {
  display: flex;
}

.flex > div {
  flex: 1 1 100px;
}

.container > div {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ddd;
}

.card-restrict > div {
  min-width: 50px;
  max-width: 100px;  
}

.container > span {
  position: absolute;
  top: 0;
  left: 8px;
  height: 24px;
  display: flex;
  align-items: center;
  font-size: 10px;
}
<div class="container fit">
  <span>auto-fit: card grows more than 100px</span>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
<div class="container fill">
  <span>auto-fill: card does not grow to 100px when it can</span>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
<div class="container fit card-restrict">
  <span>auto-fit + min/max width: gap between cards grows indefinitely</span>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
<div class="container fill card-restrict">
  <span>auto-fill + min/max width: card does not grow to 100px when it can</span>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
<div class="container flex card-restrict">
  <span>flex + min/max width: it does not work when overflow</span>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

There's also a flex version. This is how it's expected to work if cards don't overflow. Is it possible to achieve this flex-ish behavior in CSS grid?

0

There are 0 best solutions below