css grid only columns, no wrap and with auto-fill covering end gap

Viewed 624

Hi so I want to show a random number of articles in columns without wrapping but filling the extra space at the end.

The articles has to be shown every 4 of them taking the entire available width and then, by scrolling horizontally you can move to the next 4 and so on. If there are less than 4 or any multiple of it, I want the remainder to be filled empty.

So My try was this:

section {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(25%, 1fr));
  grid-auto-flow: column;
  overflow:scroll;
 }
 
 article {
 background-color: lightblue;
 margin: 10px;
 white-space: nowrap;
 height: 40px;
 }
<section>
  <article>Article 1</article>
  <article>Article 2</article>
  <article>Article 3</article>
  <article>Article 4</article>
  <article>Article 5</article>
  <article>Article 6</article>
</section>

As you can see, the first 4 columns are properly rendered, the overflown ones, are not taking anymore 25% of the space (to fit 1/4) and there are no extra spaces filled after the last 2. (in this case, there should be 2 more white)

Is it there anything I can do to achieve this with CSS Grid? Remember the total space available is dynamic as well as the number of articles. Ideally I would like Grid to always render multiples of 4 columns covering the gap.

1 Answers

Use grid-auto-columns: 25% then consider a pseudo element on the first element of each group to create the extra space:

section {
  display: grid;
  grid-auto-columns: calc((100% - 3*10px)/4); /* we remove 3 gaps here */
  grid-gap: 10px;
  grid-auto-flow: column;
  overflow: auto;
}

article {
  background-color: lightblue;
  white-space: nowrap;
  margin:10px 0;
  height: 40px;
  position:relative;
}

article:nth-child(4n + 1)::before {
  content:"";
  position:absolute;
  left:0;
  top:0;
  height:1px; /* a small height */
  width:calc(400% + 3*10px); /* we consider 3 gaps here */
  pointer-events: none; /* avoid any interaction */
}
<section>
  <article>Article 1</article>
  <article>Article 2</article>
  <article>Article 3</article>
  <article>Article 4</article>
  <article>Article 5</article>
  <article>Article 6</article>
</section>

<section>
  <article>Article 1</article>
  <article>Article 2</article>
  <article>Article 3</article>
  <article>Article 4</article>
  <article>Article 5</article>
  <article>Article 6</article>
  <article>Article 7</article>
  <article>Article 8</article>
</section>

<section>
  <article>Article 1</article>
  <article>Article 2</article>
  <article>Article 3</article>
</section>

Related