首页 > 解决方案 > Re-ordering grid items

问题描述

I have task to do in GRID css (the task main goal is to do this in GRID, not flex etc). I have two columns in my GRID, every column has own divs, but it is not important, because I already did everything. Important thing is to make RWD. In the RWD I need combina both columns to one (already did) and reverse them. How to reverse column B with all divs to be at the top of new column??

How to reverse column B with all divs to be at the top of new column??

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.row {
  float: left;
  width: 49%;
}

.column {
  border: 1px solid red;
  height: 40px;
}

@media only screen and (max-width: 600px) {
  .row {
    width: 70%;
  }
}
<div class="row">
  <div class="column">A1</div>
  <div class="column">A2</div>
</div>
<div class="row">
  <div class="column">B1</div>
  <div class="column">B2</div>
</div>

标签: htmlcssgridcss-grid

解决方案


You can use grid-template-areas and a media query to make it work.

jsFiddle demo

.row {
  display: grid;
  grid-template-areas: " a1 b1 " 
                       " a2 b2 ";
}

@media ( max-width: 500px) {
  .row { grid-template-areas: " b1" "b2" "a1" "a2" ;}
}

.row> :nth-child(1) { grid-area: a1; }
.row> :nth-child(2) { grid-area: a2; }
.row> :nth-child(3) { grid-area: b1; }
.row> :nth-child(4) { grid-area: b2; }

/* just decorative styles */
.row {
  grid-gap: 5px;
  grid-auto-rows: 50px;
}
.column {
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: lightgreen;
}
<div class="row">
  <div class="column">A1</div>
  <div class="column">A2</div>
  <div class="column">B1</div>
  <div class="column">B2</div>
</div>

These posts will help you understand how grid-template-areas works:


推荐阅读