Home > Mobile >  How to specify a preferred column for items in grid
How to specify a preferred column for items in grid

Time:06-28

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 >
  <div >Item 1</div>
  <div >Item 3</div>
  <div >Item 5</div>
  <div >Item 7</div>
  <div >Item 9</div>
  <div >Item 2</div>
  <div >Item 4</div>
  <div >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?

CodePudding user response:

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 >
  <div >Item 1</div>
  <div >Item 3</div>
  <div >Item 5</div>
  <div >Item 7</div>
  <div >Item 9</div>
  <div >Item 2</div>
  <div >Item 4</div>
  <div >Item 6</div>
  <div >Item 10</div>
  <div >Item 11</div>
</div>

  • Related