Search code examples
htmlcssflexboxcss-grid

Grid : force cell width of second row independant


I have this code that displays a row with multiple columns. When the width of the screen goes below a limit (with media-queries) I would like certain cells to pass into a second line but with widths independent of the first line.

HTML

<div class="grid">
    <div class="c1">1</div>
    <div class="c2">2</div>
    <div class="c3">3</div>
    <div class="c4">4</div>
    <div class="c5">5</div>
    <div class="c6">6</div>
    <div class="c7">7</div>
</div>

CSS

.grid {display: grid; width: 100%; grid-template-columns: 50px auto 70px 250px 60px 60px 60px;}
@media screen and (max-width: 1070px) {
.grid {grid-template-columns: 50px auto 70px 250px;}
.grid .c5 {grid-column-start: 1;}
}

Result large screen :

+-----------------------------------+
| 1 |   2   | 3 |   4   | 5 | 6 | 7 |
+-----------------------------------+

Result screen < 1070px (not what I want) : I have a line break in cells 5,6 and 7 but their width depends on the width of the column above the first line.

+-----------------------------------+
| 1 |       2      | 3 |      4     |
+-----------------------------------+
| 5 |       6      | 7 |
+-----------------------------------+

Is it possible to have this result with for example a width of 33% for the columns of the second row like this from this HTML code?

+-----------------------------------+
| 1 |       2      | 3 |      4     |
+-----------------------------------+
|      5    |      6     |    7     |
+-----------------------------------+

Solution

  • You need to wrap the required elements in a separate div which, at larger sizes is opened up with display: contents.

    At the lower width, we move the wrapper to the second row, make it full width and then apply flexbox and make the contents equal width.

    .wrap {
      display: contents;
    }
    
    [class^="c"] {
      border: 1px solid green;
      text-align: center;
    }
    
    .grid {
      display: grid;
      grid-template-columns: 50px auto 70px 250px repeat(3, 60px);
    }
    
    @media screen and (max-width: 1070px) {
      .grid {
        grid-template-columns: 50px auto 70px 250px;
      }
      .grid .wrap {
        grid-column: 1 / -1;
        display: flex;
      }
      .wrap div {
        flex: 1;
      }
    }
    <div class="grid">
      <div class="c1">1</div>
      <div class="c2">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
      <div class="c3">3</div>
      <div class="c4">4</div>
      <div class="wrap">
        <div class="c5">5</div>
        <div class="c6">6</div>
        <div class="c7">7</div>
      </div>
    </div>