Home > front end >  css grid-column span doesn't work well with auto-fit or auto-fill
css grid-column span doesn't work well with auto-fit or auto-fill

Time:02-11

I achieve grid wrapping by using auto-fit. Now I have a special div where it takes two column. Now when ever the grid is suppose to wrap to one column, the even div's disappears

Now you can see it here when viewport is below 670px the pink box disappears.

How can I solve this problem?

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;

}

.special-box {
  background-color: purple;
  grid-column: span 2;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
 <div ></div>
</div>

CodePudding user response:

You need to add a media query to remove the span 2 which is forcing your grid to always have 2 columns with the second one empty

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;

}

.special-box {
  background-color: purple;
}

@media (min-width:650px) {
  .special-box {
   grid-column: span 2;
  }
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
 <div ></div>
</div>

CodePudding user response:

The problem you're having is due to Grid Blowout.

The code snippet tool on SO has a viewport size that is too small for the boxes, the pink grid elements are pushed to the right side outside of the viewable area since they are on the odd indexes. If you run the code snippet tool in full screen and then zoom in and out with CNTRL mousewheel you can see this in action.

Here is an article that explains the topic quite well.

The fr field in repeat(auto-fill, minmax(300px, 1fr)) determines if an element will fill the rest of the row when this happens, you can avoid this problem by changing 1fr to 0fr like so:

.grid {
  gap: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 0fr));
}

.box,
.special-box {
  height: 200px;
}

.box:nth-child(even) {
  background-color: pink;

}

.box:nth-child(odd) {
  background-color: orange;
}

.special-box {
  background-color: purple;
  grid-column: span 2;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
 <div ></div>
</div>

  • Related