Search code examples
htmlcssflexboxcss-grid

Is it possible to auto-fill when aligning one item on the top right side with Flexbox or CSS Grid?


First of all, apologies for my English. It's not my first language and I'm struggling to properly describe the problem I am facing. I've tried searching for similar questions, but was unable to find anything - partially because I am unsure what to exactly search for... I will include drawings to hopefully clarify myself better.

I have an application with a bunch of rows of content - it's pretty linear, each has its own div (I know, I know..). These divs are generated based on the incoming data, so it's not always the same amount of rows. One of them is a comments/notes section. I want to change it so that on higher resolutions, the comment section gets its own column to the right to make the most out of the screen space.

Now, I have managed to get the comment section on the right-hand side with CSS Grid. However, the problem I run into with this solution is that it still uses up the row space from the comment section on the left-hand side, resulting in whitespace. I know I can use grid-row to assign row positions, but since it is not a set amount of rows, I am unsure how to proceed. Should I write a JS function to add +1 for every new row, or am I overthinking things and is there a much simpler solution for my problem? FYI, I have tried Flexbox as well but ran into similar problems. I feel like I'm missing something incredibly obvious here, but I have post-covid brain fog and it's been a struggle.

Here's a quick sketch to hopefully better show what I mean..

Thank you in advance.


Solution

  • You could set grid-row-end to a ridiculously high number, so that the comment section will always cover enough rows for the left side. This works as long as you have no row-gap because if you do have row-gap, there would be lots of gaps created between all the rows created from the high grid-row-end value.

    .container {
      display: grid;
    }
    @media (min-width: 20rem) {
      .container {
        grid-template-columns: repeat(2, 1fr);
      }
    }
    
    .row {
      outline: 1px solid green;
      grid-column-start: 1;
    }
    
    .comments {
      outline: 1px solid red;
      height: 15rem;
      grid-column-start: 2;
      grid-row-start: 1;
      grid-row-end: 999;
    }
    <div class="container">
      <div class="row">Row</div>
      <div class="row">Row</div>
      <div class="row">Row</div>
      <div class="comments">Comments</div>
      <div class="row">Row</div>
      <div class="row">Row</div>
      <div class="row">Row</div>
      <div class="row">Row</div>
    </div>