WreewanMorhee
WreewanMorhee

Reputation: 77

Make Grid Item Auto Fill

sorry I'm very new to grid-layout
I have a layout that I believe it is really easy for grid system
but I have no idea how to modify it for my layout:

the layout has three type:

  1. if only one item: full width, full height

  2. if two items, left and right; 50% width, full height

  3. if three items, correct code is below

.container {
   display: grid;
   width: 200px;
   height: 200px;
     grid-template-columns: 1fr 1fr;
     grid-template-rows: 50% 50%;
     grid-gap: 8px;
}

.a {
        grid-column: 1;
        grid-row: 1 / 3;
    background: red;
}
.b {
        grid-column: 2;
        grid-row: 1;
    background: blue;
}
.c {
        grid-column: 2;
        grid-row: 2;
    background: green;
}
<div class="container">
  <div class="a"></div>
  <div class="b"></div>
  <div class="c"></div>
</div>

code above is for type 3 and is really correct
how should I modify it let it fit type 1 and 2 ??

Upvotes: 1

Views: 897

Answers (1)

Temani Afif
Temani Afif

Reputation: 272909

You can do it like below:

.container {
  display: inline-grid;
  margin:5px;
  vertical-align:top;
  width: 200px;
  height: 200px;
  grid-gap: 8px;
}

.a { background: red;}
.b { background: blue;}
.c { background: green;}

/* when 2 items we add another column*/
.container :nth-child(2):nth-last-child(1) {
  grid-column:2;
}
/* when 3 items we add another row as well */
.container :nth-child(3):nth-last-child(1) {
  grid-row:2;
  grid-column:2;
}
/* when 3 items, the first one will span 2 rows*/
.container :first-child:nth-last-child(3) {
  grid-row:span 2;
}
<div class="container">
  <div class="a"></div>
</div>

<div class="container">
  <div class="b"></div>
</div>

<div class="container">
  <div class="c"></div>
</div>

<div class="container">
  <div class="a"></div>
  <div class="b"></div>
</div>

<div class="container">
  <div class="b"></div>
  <div class="c"></div>
</div>

<div class="container">
  <div class="a"></div>
  <div class="c"></div>
</div>

<div class="container">
  <div class="a"></div>
  <div class="b"></div>
  <div class="c"></div>
</div>

Upvotes: 1

Related Questions