skip to Main Content

I have the following code to sort two types of equal amounts of elements. However, they are all clumped up. Is there a way to put them into a single column alternating types?

.item1 {
  grid-area: myArea1;
}

.item2 {
  grid-area: myArea2; 
}

.item1, .item2 {
  opacity: 0.2;
}

.grid-container {
  display: grid;
  grid-template-areas: 'myArea1' 'myArea2';
  grid-gap: 10px;
  background-color: #2196F3;
  padding: 10px;
}
<div class="grid-container">
  <div class="item1">1</div>
  <div class="item1">11</div>
  <div class="item1">111</div>
  <div class="item1">1111</div>
  <div class="item2">2</div>
  <div class="item2">22</div>
  <div class="item2">222</div>
  <div class="item2">2222</div>
</div>

I’m open to other non-grid, but pure (S)CSS solutions. The number of items is dynamic.

2

Answers


  1. A hacky way like my previous answer

    .item1 {
      grid-column: 1;
    }
    
    .item2 {
      grid-column: 2;
      align-self: end;
    }
    
    
    .grid-container {
      display: grid;
      grid-template-columns: 0 auto;
      grid-auto-rows: 2lh;
      grid-auto-flow: dense;
      background-color: #2196F3;
      padding: 10px;
    }
    <div class="grid-container">
      <div class="item1">1</div>
      <div class="item1">11</div>
      <div class="item1">111</div>
      <div class="item1">1111</div>
      <div class="item2">2</div>
      <div class="item2">22</div>
      <div class="item2">222</div>
      <div class="item2">2222</div>
    </div>
    Login or Signup to reply.
  2. As long as you know generally how many (or can calculate how many programmatically, you could try using columns: 2; (or however many columns) on your grid-container div’s css.

    .grid-container {
      columns: 2;
    }
    

    Like this jsfiddle example

    See the documentation on columns

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search