Home > OS >  How to set three columns in one particular row in css grid?
How to set three columns in one particular row in css grid?

Time:07-24

I want to layout my divs in that order:

a b      <- two columns
c c      <- one column
d e f    <- three columns
g g      <- one column

section { 
  display:grid;    
  grid-template-areas: 'a b' 'c c' 'd e f' 'g g';
}
div { height:20px; }
div:nth-of-type(1) {background:red;grid-area:a;}
div:nth-of-type(2) {background:green;grid-area:b;}
div:nth-of-type(3) {background:yellow;grid-area:c;}
div:nth-of-type(4) {background:pink;grid-area:d}
div:nth-of-type(5) {background:aqua;grid-area:e;}
div:nth-of-type(6) {background:black;grid-area:f;}
div:nth-of-type(7) {background:black;grid-area:g;}
<section>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</seciton>

I use grid-area to do that and I was able to do that only with two columns or one column:

a b      <- two columns
c c      <- one column
d e      <- two columns
g g      <- one column

But when I add f area after e then everything breaks.

I try to order three columns but I losing the two columns a b and b is larger than a:

a b b
c c c
d e f
g g g

section { 
  display:grid;    
  grid-template-areas: 'a b b' 'c c c' 'd e f' 'g g g';
}
div { height:20px; }
div:nth-of-type(1) {background:red;grid-area:a;}
div:nth-of-type(2) {background:green;grid-area:b;}
div:nth-of-type(3) {background:yellow;grid-area:c;}
div:nth-of-type(4) {background:pink;grid-area:d}
div:nth-of-type(5) {background:aqua;grid-area:e;}
div:nth-of-type(6) {background:black;grid-area:f;}
div:nth-of-type(7) {background:black;grid-area:g;}
<section>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</seciton>

Is it possible to do this kind of layout with css grid?

CodePudding user response:

You want some rows to be 1 column, some to be 2 and some to be 3.

You have to find the lowest number of columns that would suit all 3. In this case that is 6.

So a single column can be defined as 'x x x x x x', two columns as 'x x x y y y' and three columns as 'x x y y z z'.

section {
  display: grid;
  grid-template-areas: 'a a a b b b' 'c c c c c c' 'd d e e f f' 'g g g g g g';
}

div {
  height: 20px;
}

div:nth-of-type(1) {
  background: red;
  grid-area: a;
}

div:nth-of-type(2) {
  background: green;
  grid-area: b;
}

div:nth-of-type(3) {
  background: yellow;
  grid-area: c;
}

div:nth-of-type(4) {
  background: pink;
  grid-area: d
}

div:nth-of-type(5) {
  background: aqua;
  grid-area: e;
}

div:nth-of-type(6) {
  background: black;
  grid-area: f;
}

div:nth-of-type(7) {
  background: black;
  grid-area: g;
}
<section>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  </seciton>

  • Related