2

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.

1

1 Answer 1

8

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>

Sign up to request clarification or add additional context in comments.

4 Comments

This looks good for the above example, but would this work for example if I wanted it to look the same as grid-template-areas: 'A B C' 'A D E'?
@DavidCallanan i would say yes ;) it need som code adjustement but it can be done with flex ... here is an example : jsfiddle.net/gxntjfr0/2 adjust the screen size to see both layout
Nice! But is it possible to have a flex-direction of row and column at the same time so that I can do more complex layouts?
@DavidCallanan within the same container no :) you can have eiher row or column, but if you have nested container you can ... by the way there is a lot of other property that may help to adjust the layout using flexbox ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.