Search code examples
csscss-grid

How to specify a preferred column for items in grid


I want to have my blue items prefer to be placed on the left side and all my red items prefer to be placed the right side. All items should start from the first row and if there are more one type, they should be able to use the other column.

With some help from @Temani Afif, I tried this, but it doesn't work as they are not wrapping into the other column.

.grid {
  display: grid;
  grid-auto-flow: dense;
  width: 300px;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  grid-gap: .25rem;
}

.foo {
  background: blue;
  grid-column-start: 1;
  grid-column-end: 1;
}
.bar {
  background: red;
  grid-column-start: 2;
  grid-column-end: 2;
}

.item {
  padding: 0.5rem 1rem;
  color: white;
}
<div class="grid">
  <div class="item foo">Item 1</div>
  <div class="item foo">Item 3</div>
  <div class="item foo">Item 5</div>
  <div class="item foo">Item 7</div>
  <div class="item foo">Item 9</div>
  <div class="item bar">Item 2</div>
  <div class="item bar">Item 4</div>
  <div class="item bar">Item 6</div>
</div>

What I want is something like this:

enter image description here

Here the red items start from the first row like the blue items and the blue items can wrap into the second column if there is an uneven amount of items.

Is this possible with css?


Solution

  • Specify the position of the red only and use grid-auto-flow: dense. Then the trick is to consider order as well

    .grid {
      display: grid;
      width: 300px;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      grid-auto-flow: dense;
      grid-gap: .25rem;
    }
    
    .foo {
      background: blue;
    }
    
    .bar {
      background: red;
      grid-column-start: 2;
      order: -1;
    }
    
    .item {
      padding: 0.5rem 1rem;
      color: white;
    }
    <div class="grid">
      <div class="item foo">Item 1</div>
      <div class="item foo">Item 3</div>
      <div class="item foo">Item 5</div>
      <div class="item foo">Item 7</div>
      <div class="item foo">Item 9</div>
      <div class="item bar">Item 2</div>
      <div class="item bar">Item 4</div>
      <div class="item bar">Item 6</div>
      <div class="item foo">Item 10</div>
      <div class="item foo">Item 11</div>
    </div>