【问题标题】:CSS grid auto expandCSS 网格自动展开
【发布时间】:2020-07-18 01:51:22
【问题描述】:

我使用 CSS 网格创建了一个 12 列的网格。但是,现在我坚持使用 auto width (Auto expand until the end) 类。谁能告诉我有什么办法或解决方法来实现它?

.box {background-color: #20262e; color: #fff; padding: 2rem;}

.row {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: repeat(12, 1fr);
}

.col-6 {
    grid-column-end: span 6;
}

.col-2 {
    grid-column-end: span 2;
}

.col {
  background-color: red !important;
    /*  ??? */
}
<div class="row">
  <div class="box col-6">Parent A</div>
  <div class="box col-6">
    <div class="row">
      <div class="box col-6">Child A</div>
      <div class="box col-6">Child B</div>
    </div>
  </div>

  <div class="box col-2">A</div>
  <div class="box col">AUTO FILL</div>
  <div class="box col-2">B</div>
</div>

【问题讨论】:

  • 这是一个 flexbox 工作,你不能用 CSS 网格来做到这一点

标签: html css css-grid


【解决方案1】:

正如@Temani Afif 在 cmets 中所说的那样 - 这是flex 的作品。

使用固定的span,如col-8

.box {background-color: #20262e; color: #fff; padding: 2rem;}

.row {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: repeat(12, 1fr);
}

.col-6 {
    grid-column-end: span 6;
}

.col-2 {
    grid-column-end: span 2;
}

.col-8 {
  background-color: red !important;
  grid-column-end: span 8;
}
<div class="row">
  <div class="box col-6">Parent A</div>
  <div class="box col-6">
    <div class="row">
      <div class="box col-6">Child A</div>
      <div class="box col-6">Child B</div>
    </div>
  </div>

  <div class="box col-2">A</div>
  <div class="box col-8">AUTO FILL</div>
  <div class="box col-2">B</div>
</div>

使用flex

现在就像Bootstrap 4 Grid system。将flex-grow: 1; 用于自动宽度伸缩元素。

* {
  box-sizing: border-box;
}

.container {
  padding: 0 15px;
}

.box {
  background-color: #20262e;
  background-clip: content-box;
  color: #fff;
  min-height: 100px;
  padding: 0 15px 30px 15px;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -15px;
  margin-left: -15px;
}

.col-6 {
  flex: 0 0 50%;
  max-width: 50%;
}

.col-2 {
  flex: 0 0 16.66667%;
  max-width: 16.66667%;
}

.col {
  background-color: red !important;
  flex-basis: 0;
  flex-grow: 1;
  min-width: 0;
  max-width: 100%;
}
<div class="container">
  <div class="row">
    <div class="box col-6">Parent A</div>
    <div class="box col-6">
      <div class="row">
        <div class="box col-6">Child A</div>
        <div class="box col-6">Child B</div>
      </div>
    </div>

    <div class="box col-2">A</div>
    <div class="box col">AUTO FILL</div>
    <div class="box col-2">B</div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2020-01-14
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多