Home > OS >  How do I limit column span to available columns in CSS grid?
How do I limit column span to available columns in CSS grid?

Time:10-16

I want to create a grid with fixed column and row sizes, which contains items that can either span 1, 2, 3 or 4 columns (and 1 or 2 rows).

This is fine as long as the .grid is wide enough to fit at least as many columns as the largest item, e.g the .grid is 600px gap, and there's an item that spans 2 columns.

However, when the grid gets smaller, the grid-column: span <more than available columns> the column just collapses (See snippet below for demo).

Question: Is there a way to say that an item "should span X columns if possible, otherwise X-1 columns"? So a "triple" item in my example would instead only cover 2 columns, if that's what's available.

If not, is there another prefered way of approaching this problem?

NOTE: I know I can solve this with some JavaScript and set the column span for the different items based on the container size, e.g using a ResizeObserver. But I'd really prefer a CSS-only solution to this.

Also, media queries is not an option since the grid will be sized based on other constraints rather than just the viewport size.

function smallGrid() {
  document.querySelector(".grid").style.width = "300px";
}

function largeGrid() {
  document.querySelector(".grid").style.width = "440px";
}
.grid {
  --size: 100px;
  
  display: grid;
  grid-template-columns: repeat(auto-fill, var(--size));
  grid-auto-rows: var(--size);
  gap: 10px;
  grid-auto-flow: row;
  justify-content: center;
}

.item {
  border: 1px solid gray;
  box-shadow: 3px 3px 5px lightgray;
}

.item.double {
  grid-column: span 2;
}

.item.triple {
  grid-column: span 3;
}

.item.quad {
  grid-column: span 4;
}
<section  style="width: 440px">
  <article >3x1</article>
  <article >1x1</article>
  <article >1x1</article>
  <article >2x1</article>
  <article >1x1</article>
  <article >4x1</article>
</section>
<section>
  <button onclick="largeGrid()">Large Grid</button>
  <button onclick="smallGrid()">Small Grid</button>
</section>

CodePudding user response:

Okay I just noticed this question which is basically the same as mine. It's been around for 3 years and so far the best answer seems to be "not possible without media queries", which translates to "not possible without js (or container queries)" for me.

CodePudding user response:

you can span it to the end with the help of negative indexes

grid-column: 1/-1;
  • Related