How to make the last items in my CSS grid stretch full width with equal spacing?

南笙酒味 提交于 2021-01-28 05:40:19

问题


I am new to using CSS grid and have stumbled across a problem that I can't find an answer online. What I am trying to achieve is a 7 column layout, and the remaining items to stretch in width equally to fill up the remaining space.

I have attempted to use auto-fill & auto-fit as I found online, but this didn't tackle my problem. I am not sure if this can be achieved in CSS grid and I may have to use flexbox?

I would like "Eight", "Nine" and "Ten" to stretch full width to be inline with the row above.

.wrapper {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-auto-rows: auto;
}

* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
}

.wrapper>div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
  <div>Six</div>
  <div>Seven</div>
  <div>Eight</div>
  <div>Nine</div>
  <div>Ten</div>
</div>

回答1:


Can't be done automatically with grid for these reasons:

  • Aligning grid items across the entire row/column (like flex items can)
  • Place wrapping items in the center of the grid

It's the opposite of this common problem:

  • Equal width flex items even after they wrap

May be possible with flex.

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.wrapper > div {
  flex: 1 0 14%;
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
}

* {
  box-sizing: border-box;
}
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
  <div>Six</div>
  <div>Seven</div>
  <div>Eight</div>
  <div>Nine</div>
  <div>Ten</div>
</div>


来源:https://stackoverflow.com/questions/63471747/how-to-make-the-last-items-in-my-css-grid-stretch-full-width-with-equal-spacing

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