sdvnksv
sdvnksv

Reputation: 9668

How can I reorder a grid of columns?

What I have is a two-column layout with several items inside:

.grid {
  column-count: 2;
}

.grid-item {
  break-inside: avoid;
  height: 50px;
  margin-bottom: 10px;
  background-color: green;
  text-align: center;
  line-height: 50px;
  color: white;
}
<div class="grid">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
</div>

https://codepen.io/Deka87/pen/RgdLeZ

Now I need an ability to reorder those items inside the columns with CSS only (so they were in a different order on different screen resolutions), so I thought I can do this with:

.grid {
  display: flex;
  flex-direction: column;
  column-count: 2;
}
.grid-item:nth-child(1) {
  order: 5;
}

Obviously, this didn't work and broke the 2-column layout. Anybody tried to solve this before? Any chance I can get this working?

PS: Items on the same line should not be of the same height (I could have used simple floats in this case). Sorry for not specifying in the beginning.

Upvotes: 5

Views: 1444

Answers (2)

lumio
lumio

Reputation: 7575

I tend to use flexbox for this

.grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: flex-start;
}
.grid-item {
  box-sizing: border-box;
  width: calc( 50% - 5px );
  min-height: 50px;
  margin-bottom: 10px;
  background-color: green;
  text-align: center;
  line-height: 50px;
  color: white;
}

.grid-item:nth-child(1) {
  order: 5;
}
<div class="grid">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
</div>  

The flex syntax is widely supported and super flexible.

Upvotes: 1

Michael Benjamin
Michael Benjamin

Reputation: 371223

Without a fixed height on the container, a column of flex items won't know where to wrap. There's nothing to cause a break, so items will continue expanding the single column.

Also, column-count and display: flex represent two different CSS technologies. column-count is not a valid property in a flex container.

CSS Grid Layout may be useful to you:

re-size the screen width to trigger the media query

revised codepen

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: repeat(3, auto);
  grid-auto-rows: 50px;
  grid-auto-flow: column;
  grid-gap: 10px;
}

.grid-item {
  background-color: green;
  text-align: center;
  line-height: 50px;
  color: white;
}

@media ( max-width: 500px) {
  .grid-item:nth-child(2) {
    order: 1;
    background-color: orange;
  }
}
<div class="grid">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
</div>

Upvotes: 3

Related Questions