0

I've come across an example of grid layout and don't understand why adding grid gap to rows and columns causes the row items to overflow the container (which I understand) but not the column items; instead the container expands with no overflow.

body {
  padding: 20px;
}

.grid-container {
  border: 5px solid black;
  font-family: avenir, sans-serif;
  font-weight: bold;
  display: grid;
  grid-template-columns: repeat(4, 25%);
  grid-template-rows: 100px 100px;
  gap: 20px;
}

.grid-item {
  padding: 10px 20px;
}

.grid-item:nth-child(1) {
  background: darkcyan;
}

.grid-item:nth-child(2) {
  background: turquoise;
}

.grid-item:nth-child(3) {
  background: aquamarine;
}

.grid-item:nth-child(4) {
  background: lightgreen;
}

.grid-item:nth-child(5) {
  background: mediumseagreen;
}
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
</div>
Charles Lavalard
  • 2,061
  • 6
  • 26
Smithy
  • 1,157
  • 3
  • 11
  • 18

1 Answers1

0

You should use fr units for that kind of use in grid-template-columns: repeat(4, 1fr);

1fr represent 1 fraction of the available space

body {
  padding: 20px;
}

.grid-container {
  border: 5px solid black;
  font-family: avenir, sans-serif;
  font-weight: bold;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: 100px 100px;
  grid-gap: 20px;
}

.grid-item {
  padding: 10px 20px;
}

.grid-item:nth-child(1) {
  background: darkcyan;
}

.grid-item:nth-child(2) {
  background: turquoise;
}

.grid-item:nth-child(3) {
  background: aquamarine;
}

.grid-item:nth-child(4) {
  background: lightgreen;
}

.grid-item:nth-child(5) {
  background: mediumseagreen;
}
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
</div>
Charles Lavalard
  • 2,061
  • 6
  • 26
  • Yes I get that. But why does the overflow occur with rows and not columns? – Smithy May 19 '21 at 18:36
  • Yeah Let's say the width of your grid is 200px you take 25% per column so each tile is 50px but add to that your `20px` and there you have your `60px` overflow – Charles Lavalard May 19 '21 at 18:41
  • I realised that the question needs re-stating. It's the cross-axis (Y-axis) that is not overflowing outside its container. Increasing the row gap makes the container expand to accommodate the extra space but only in the cross-axis. – Smithy May 19 '21 at 20:51