Search code examples
htmlcssgrid-layoutcss-grid

CSS grid: wrap three divs simultaneously


With CSS grid, how can I style three divs to wrap at the same time when the screen gets smaller ?

That means to go from this:

+---------+--+---------+--+---------+
|   div   |  |   div   |  |   div   |
+---------+--+---------+--+---------+

to this:

+-----+
| div |
+-----+
|     |
+-----+
| div |
+-----+
|     |
+-----+
| div |
+-----+

without first going through this intermediary step:

+---------+--+---------+
|   div   |  |   div   |
+---------+--+---------+
|         |  |         |
+---------+--+---------+
|   div   |  |         |
+---------+--+---------+

With that starter code:

.wrapper {
  display: grid;
  grid-gap: 10px;
}
<div class="wrapper">
  <div class="box">box 1</div>
  <div class="box">box 2</div>
  <div class="box">box 3</div>
</div>

https://jsfiddle.net/jLz0aqmj/1/


Solution

  • Use a media query to switch the number of columns from three to one.

    revised jsFiddle demo

    .wrapper {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-gap: 10px;
    }
    
    @media ( max-width: 500px ) {
      .wrapper {
        grid-template-columns: 1fr;
      }
    }
    
    .box {
      background-color: lightgreen;
    }
    <div class="wrapper">
      <div class="box">box 1</div>
      <div class="box">box 2</div>
      <div class="box">box 3</div>
    </div>