【问题标题】:How to make grid column fit the rest of the space如何使网格列适合其余空间
【发布时间】:2020-12-10 14:06:00
【问题描述】:

我有一个包含三列的网格包装器,其中第一列最大,宽度为 2fr,第二列和第三列的大小相同,它们都占用 1fr 的宽度。我想要的是创建一个具有动态列数的网格模板,例如,如果我删除其中一列,其余列应该同样采用剩余大小。 这是我迄今为止尝试过的小提琴

.wrapper {
  display: grid;
  height: 100px;
  width: 300px;
  grid-template-columns: 2fr 1fr 1fr;
  border: 1px solid black;
}

.first {
  background-color: red;
}

.second {
  background-color: lightblue;
}

.third {
  background-color: lightgreen;
}
<div class="wrapper">
  <div class="first">
  1
  </div>
  <div class="second">
  2
  </div>
 <!-- <div class="third">
  3
  </div> -->
</div>

Fiddle

我已尝试使用 grid-template-columns: 2fr auto auto,但效果不佳。预期的结果是这样的

但实际结果是这样的

知道如何解决这个问题吗?所有示例将不胜感激!

【问题讨论】:

  • 通常这在 CSS-Grid 中是不可能的。事实上,这就是 flexbox 的用途,
  • 寻求代码帮助的问题必须包括在问题本身中重现它所需的最短代码,最好是在堆栈片段中。尽管您提供了一个链接,但如果它变得无效,那么您的问题对于未来遇到同样问题的其他 SO 用户将毫无价值。见Something in my website/example doesn't work can I just paste a link
  • @Paulie_D 好的,谢谢,我会编辑我的问题。
  • @Paulie_D 我也会对 flexbox 示例感到满意!
  • 关于“剩余宽度”有很多问题。

标签: css css-grid


【解决方案1】:

依赖隐式列:

.wrapper {
  display: grid;
  height: 100px;
  width: 300px;
  grid-template-columns: 50%; /* one explicit column */
  grid-auto-columns:1fr; /* implicit column created when needed */
  grid-auto-flow:column;
  border: 1px solid black;
}

.first {
  background-color: red;
}

.first:last-child {
   grid-column:span 2; /* full width if alone */
}

.second {
  background-color: lightblue;
}

.third {
  background-color: lightgreen;
}
<div class="wrapper">
  <div class="first">
  1
  </div>
  <!--<div class="second">
  2
  </div>-->
 <!-- <div class="third">
  3
  </div> -->
</div>

<div class="wrapper">
  <div class="first">
  1
  </div>
  <div class="second">
  2
  </div>
 <!-- <div class="third">
  3
  </div> -->
</div>


<div class="wrapper">
  <div class="first">
  1
  </div>
  <div class="second">
  2
  </div>
 <div class="third">
  3
  </div> 
</div>

【讨论】:

  • 这真是太棒了,谢谢。我知道我没有在问题上提到这一点,但是如果我删除 2 个盒子怎么办?那么剩下的盒子将只占用 50% 的包装而不是 100%。我该如何解决?
  • 很抱歉打扰你了,但是如果其他 div 是单独的呢?我已经尝试过类似.wrapper &gt; div:last-child { grid-column:span 2; /* full width if alone */ } 的东西,但这并不好:(
  • @Milos 如果您希望它与任何 div 一起使用,请使用 div:only-child {}div:first-child:last-child {}
  • 是的,这就是我想要的。非常感谢楼主!
猜你喜欢
  • 1970-01-01
  • 2013-11-04
  • 2013-11-19
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2020-06-10
相关资源
最近更新 更多