Home > Software engineering >  How to stop grid item from stretching?
How to stop grid item from stretching?

Time:11-08

I have this simple grid:

.outGrid {
  display: grid;
  grid-gap: 40px;
  grid-template-columns: repeat(3, 1fr);
}

.item {
  width: 40px;
  height: 40px;
  background-color: grey;
}
<div class='outGrid'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>

As you can see, I've defined the grid-gap to be 40px, but each grid item stretches horizontally as page width changes. I'd like the item to not stretch and simply occupy full space, so both vertical and horizontal gaps are 40px to form a nice 3*3 grid. How to achieve that?

CodePudding user response:

Change

  grid-template-columns: repeat(3, 1fr);

To

  grid-template-columns: 40px 40px 40px

Or to any amount you want and change item width to 100%

CodePudding user response:

You could replace repeat(3, 1fr) with repeat(3, 40px):

.outGrid {
  display: grid;
  grid-gap: 40px;
  grid-template-columns: repeat(3, 40px);
}

.item {
  width: 40px;
  height: 40px;
  background-color: grey;
}
<div class='outGrid'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>

  • Related