Explaining Grid

Firefox, Chrome and Safari all support grid overlays in Devtools and they are extremely useful when building with CSS grid.

Today's scenario is: you would like to have a grid with 4 equal width columns that have a 20px gap between each column.

Basic grid

.container1 {
  display: grid;
  grid-template-columns: 200px 20px 200px 20px 200px 20px 200px;
  grid-template-rows: 150px 150px;
}

The gap property

.container2 {
  display: grid;
  grid-template-columns: 200px 200px 200px 200px;
  grid-template-rows: 150px 150px;
  gap: 20px;
}

A responsive grid

.container3 {
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
  grid-template-rows: 150px 150px;
  gap: 20px;
}
.container4 {
  display: grid;
  grid-template-columns: calc((100% - 60px) / 4) calc((100% - 60px) / 4) calc((100% - 60px) / 4) calc((100% - 60px) / 4);
  grid-template-rows: 150px 150px;
  gap: 20px;
}

The repeat() function

.container5 {
  display: grid;
  grid-template-columns: repeat(4, calc((100% - 60px) / 4));
  grid-template-rows: 150px 150px;
  gap: 20px;
}

The fr unit

.container6 {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: 150px 150px;
  gap: 20px;
}

Placing grid items

A

B

C

D

Auto-placement occurs when no placement properties are applied on the children. By default, each grid item will take up the space of 1 grid cell.

A

B

C

D

p:first-child {
  grid-column: 2 / 4;
  grid-row: 1 / 3;
}

Overlapping grid items

A

B

C

D

p:first-child { grid-column: 2 / span 2;
  grid-row: 1 / span 2;
}

p:nth-child(2) { 
  grid-column: 1 / span 2;
  grid-row: 1;
}
p:nth-child(3) { 
  grid-column: 3/ span 2;
  grid-row: 2;
}

Named grid areas

A

B

C

D

.container6 {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: 150px 150px;
  gap: 20px;
  grid-template-areas: 'a a . c'
                       '. b b c';
}

p:first-child { grid-area: a }
p:nth-child(2) { grid-area: b }
p:nth-child(3) { grid-area: c }

@hj_chen