cssjsp

Set width of unknown number of CSS Grid columns


I have an HTML Grid in a JSP that will have an unknown amount of columns from 1-3 that need to each be equal width to each other, followed by two more columns at a fixed width

Is there any way to use the grid's own CSS, for example grid-template-columns, to be able to do this? Or would I have to set it on the last two divs directly?

I know fr will make it expand to fill empty space, but I'm not sure how I could make that work with the grid-template-columns

The other alternative would be making a flexbox inside a single div, and set that column to fr, but I wanted to see if there was a way to do it with the grid first

Example mockup:

<div class="grid-div">
  <%-- A list of items, will be from 1-3 --%>
  <c:forEach items="${itemList}" var="item">
    <div>${item.info}</div>
  </c:forEach>
  <div>Checkboxes here</div>
  <div>Buttons here</div>
</div>
.grid-div {
  display: grid;
  gap: 5px;
  grid-template-columns: <something?> 120px 100px;
}

Edit for clarification: The grid as a whole is also a fixed width on the screen, with the two fixed-width columns on the right

The 1-3 variable columns need to evenly split the remaining space on the left


Solution

  • You can use the combination :nth-last-child():first-child, something like this:

    .grid-div {
      --n: 3;
      display: grid;
      grid-template-columns: repeat(var(--n), 1fr) 120px 100px;
      gap: 6px;
      &:has(:nth-last-child(3):first-child) {
        --n: 1;
      }
      &:has(:nth-last-child(4):first-child) {
        --n: 2;
      }
    
      /* decor */ 
      div {
        padding: 4px;
        text-align: center;
        border: solid 1px #ccc;
      }
      &:not(:last-child) {
        margin-bottom: 16px;
      }
    }
    <div class="grid-div">
      <div>1</div>
      <div>Checkboxes here</div>
      <div>Buttons here</div>
    </div>
    <div class="grid-div">
      <div>1</div>
      <div>2</div>
      <div>Checkboxes here</div>
      <div>Buttons here</div>
    </div>
    <div class="grid-div">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>Checkboxes here</div>
      <div>Buttons here</div>
    </div>