【问题标题】:Using CSS grid how do i make a one column layout where one element fills remaining space after all others have taken an auto width使用 CSS 网格我如何制作单列布局,其中一个元素在所有其他元素都采用自动宽度后填充剩余空间
【发布时间】:2020-05-27 15:37:03
【问题描述】:
  1. 我不想明确定义列数,以便以后添加其他自动宽度子项。
  2. 我不想使用额外的包装器。
  3. 我想在 CSS 网格而不是 flexbox 中执行(我可以在带有包装器的 flexbox 中执行)
  4. 如果您想知道它的导航栏布局

    Heres what i am trying to achieve

.container {
  display: grid;
  grid-template-columns: auto 1fr auto;
  grid-gap: 5px;
  align-items: flex-start;
  margin-bottom: 10px;
}

.item--1,
.item--3 {
  grid-column: 1fr;
  width: 100px;
}

.item--2 {
  color: #fff;
  line-height: 100px;
  text-align: center;
  font-size: 30px;
}

.item {
  height: 100px;
  background: deepskyblue;
}

@media screen and (max-width: 768px) {
  .container-1 {
    grid-template-rows: auto auto;
  }
  .item--1 {
    grid-column: 1 / 2;
  }
  .item--2 {
    grid-row-start: 2;
    grid-column: 1 / -1;
  }
  .item--3 {
    grid-column: 3 / 4;
  }
}
<div class="container">
  <div class="item item--1"></div>
  <div class="item item--2">Fill up remaining space</div>
  <div class="item item--3"></div>
</div>

【问题讨论】:

  • 这并不比您至少有代码 (stackoverflow.com/q/62044990/8620333) 的旧问题要好......这不是问题,只是一个要求列表
  • @TemaniAfif 对不起,我的错
  • 我还是不明白你为什么不想要 flexbox?你可以用 flexbox 做到这一点,而无需额外的包装器
  • @TemaniAfif 你能帮我解决这个问题吗,比如一些代码也是网格,因为这个问题只是卡在我的脑海里
  • 如果不知道元素的数量并且也不知道需要填充空间的元素,您将找不到任何使用 CSS 网格的干净代码。 Flexbox 更适合这里

标签: html css css-grid


【解决方案1】:

这是一个带有 flexbox 且没有额外包装器的想法:

.container {
  display: flex;
  grid-gap: 5px;
  margin-bottom: 10px;
}

/* this is your gap */
.item:not(:last-child) {
  margin-right: 5px;
}
/**/

.fill {
  color: #fff;
  line-height: 100px;
  text-align: center;
  font-size: 30px;
  flex-grow: 1; /* fill the remaining space */
}

.item {
  height: 100px;
  width: 100px;
  background: deepskyblue;
  margin-bottom: 5px;
}

@media screen and (max-width: 768px) {
  .container {
    flex-wrap: wrap; /* allow the wrap */
  }
  .fill {
    order: 2; /* make the element the last on*/
    flex-basis: 100%; /* 100% width */
    margin-right: 0!important;
  }
  .fill + * {
    margin-left: auto; /* keep the element on the left */
  }
}
<div class="container">
  <div class="item"></div>
  <div class="item fill">Fill up remaining space</div>
  <div class="item"></div>
  <div class="item"></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2021-07-22
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多