Home > database >  CSS grid, place item on new row in column empty on previous row
CSS grid, place item on new row in column empty on previous row

Time:10-23

Let's say I have a grid with 2 columns and an unknown number of items. something like:

.grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
}

.new-row {
    grid-column-start: 1;
}

.new-row.col-2 {
    grid-column-start: 2;
    */ Now what ??? /*
}
<div class="grid">
    <!-- unknown number of items here -->
    <div class="new-row">Column 1</div>
    <div>Column 2</div>
    <div class="new-row">Column 1</div>
    <div class="new-row col-2">Column 2</div>
    <!-- unknown number of items here -->
</div>

At some point I want to have an item in column 1, followed by an item in column 2, but on the next row. Like:

Column 1 Column 2
Column 1
Column 2

I don't know how many items will come before or after, so I can't just put the appropriate number in grid-row-start.

I can't alter the HTML, and I can't use JavaScript.

How can I achieve this?

CodePudding user response:

You can take the whole width and consider padding or margin to push the element into the second column:

.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.new-row {
  grid-column: 1;
}

.new-row.col-2 {
  grid-column: 1/-1;
  margin-left:50%; /* push to second column */
}
<div class="grid">
  <!-- unknown number of items here -->
  <div class="new-row">Column 1</div>
  <div>Column 2</div>
  <div class="new-row">Column 1</div>
  <div class="new-row col-2">Column 2</div>
  <!-- unknown number of items here -->
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related