Auto Grid columns, without wrapping to next row

匆匆过客 提交于 2021-02-05 11:40:34

问题


I want this 3 boxes to display next to each other, with same width of 381px

Their parent is .boxes and they are .box

I can do that with the following on parent:

.boxes {
   display: grid;
   grid-template-columns: repeat(3, 381px);
}

BUT:

If in future I want to add one more box, I want that .box to also be 381px wide.

I don't want to specify number 3, I want it to be infinite columns of 381px if new box appears

I want to achieve same result as:

grid-template-columns(auto-fit, 381px);

But I don't want them to wrap to next row if they can't fit.

Is it possible?


回答1:


You simply make the flow to be column like below:

.boxes {
  display: grid;
  grid-auto-columns: 381px;
  grid-auto-flow: column; /* this will do the trick */
  grid-gap: 10px;
}

.boxes>* {
  height: 50px;
  background: red;
}
<div class="boxes">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>



回答2:


Using the following couple lines of code will help you achieve that

.boxes {
    display: grid;
    gap: 10px;
    grid-auto-columns: 381px;
    grid-auto-flow: column; 
}

The grid-auto-flow property defines whether new elements added to the grid will be added as 'implicit rows' or 'implicit columns'. It's default is row, which we want to be column.

The grid-auto-columns property is the same as grid-template-columns, except that it deals with implicit columns (4th and thereon, since you defined grid to have only 3 columns, the ones that come after those 3 will be implicit columns).



来源:https://stackoverflow.com/questions/63561017/auto-grid-columns-without-wrapping-to-next-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!