Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reorder a grid of columns?

Tags:

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.

like image 709
sdvnksv Avatar asked Jul 14 '17 16:07

sdvnksv


1 Answers

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>
like image 113
Michael Benjamin Avatar answered Sep 29 '22 23:09

Michael Benjamin