David Callanan
David Callanan

Reputation: 5958

css grid layout different number of columns in each row

I have a grid container like this:

<div class="container">
    <div class="a">A</div>
    <div class="b">B</div>
    <div class="c">C</div>
    <div class="d">D</div>
    <div class="e">E</div>
</div>

I am using grid-template-areas to position them like this:

.container {
    display: grid;
    grid-template-areas:
        'a b .'
        'c d e';
}

.a {grid-area: 'a';}
.b {grid-area: 'b';}
.c {grid-area: 'c';}
.d {grid-area: 'd';}
.e {grid-area: 'e';}

Which looks like this:

_____________
| A | B |   |
| C | D | E |

However, I would like the number of columns in each row to be independent of the other rows, so I would like something like this:

grid-template-areas:
    'a b'
    'c d e';

and I would like the following result:

_____________
|  A  |  B  |
| C | D | E |

The code above does not work. The only solution I came up with was to get the lowest common denominator of the number of columns in each row: 2 x 3 = 6. Then I would repeat each area the number of times necessary:

grid-template-areas:
    'a a a b b b'
    'c c d d e e';

The problem is that I might have an lcd of two hundred or something, and this would probably be very slow at calculating and rendering.

Is there any way I can achieve this without doing the above? I still need to use one grid layout so that I can completely shift around all the elements when there are different screen sizes, which means I can't just use separate grids for each row.

Upvotes: 2

Views: 4882

Answers (1)

Temani Afif
Temani Afif

Reputation: 272648

Am not sure if you can easily do this with grid, but with flexbox it's easy to do and you can always adjust the order property to change the layout on small screens.

.container {
  display:flex;
  flex-wrap:wrap;
  height:300px;
}
.a,.b {
  flex-basis:calc(100% / 2);
}
.c,.d,.e {
  flex-basis:calc(100% / 3);
}

.container > div {
  border:1px solid;
  box-sizing:border-box;
}
<div class="container">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
  <div class="d">D</div>
  <div class="e">E</div>
</div>

Upvotes: 8

Related Questions