【问题标题】:Filling cells starting from the bottom in CSS Grid在 CSS Grid 中从底部开始填充单元格
【发布时间】:2020-07-15 15:39:31
【问题描述】:

我有一个 3 行的 CSS 网格。可能要填充的项目少于3个,我想从底部开始填充。

我创建了一个jsFiddle 供您使用,但它目前无法满足我的要求。

html, body, div {
  height: 100%;
}

div {
  display: grid;
  grid-template-columns: 1;
  grid-template-rows: repeat(3, 1fr);
  /* MISSING RULE */
}
<div>
  <p>Last item</p>
  <p>Second last item</p>
  <p>Top item</p>
</div>

实际输出:

Last item
Second last item
Top item

期望的输出:

Top item
Second last item
Last item

如果可能的话,我想对包含网格的&lt;div&gt; 应用一个规则,而不是对网格中的项目应用单独的规则。

【问题讨论】:

  • 您准备好使用grid 属性了吗?这可以用 flexbox 分两行来完成。
  • @TylerH:实际上,有多个列,因此 flexbox 解决方案需要更复杂的 HTML。
  • 您能否在此处更新您的代码以包含另一列的外观?

标签: css css-grid


【解决方案1】:

如果你想使用 CSS Grid 布局,它会是这样的。我修改了你的 HTML。您必须为网格子项在哪里开始和在哪里结束编写 CSS 属性。 grid-row-start:grid-row-end:Here is a CodePen.

  .grid-item{
      border: 2px solid red;
      border-radius: 5px;
      height: 200px;
      padding: 10px;
      width: 300px;
      margin-left: auto;
      margin-right: auto;
      display: grid;
      grid-template-columns: 1fr;
      grid-template-rows: repeat(3, 1fr);
    }
    .grid-item p{
      margin: 0;
    }
    .grid-item .first-item{
      grid-row-start: 1;
    }
    .grid-item .last-item{
      grid-row-start: 3;
    }
<div class="grid-item">
        <p class="last-item">Last item</p>
        <p class="second-item">Second last item</p>
        <p class="first-item">Top item</p>
    </div>
    

如果你想使用flexbox,它将使用行代码。

<div>
    <p>Last item</p>
    <p>Second last item</p>
    <p>Top item</p>
</div>

CSS为此

div{
    display: flex;
    flex-direction: column-reverse;
}

flex-direction CSS 属性设置弹性项目如何放置在弹性容器中,定义主轴和方向(正常或反向)。

【讨论】:

  • OP 说项目的数量是动态的,所以你不会知道如何应用 n-item 类。
【解决方案2】:

CSS Grid 中没有 column-reverse 函数,就像 flexbox 中一样。

因此,使用容器中的单个规则是不可能让网格区域从底部开始填充容器的。

这是它在 flexbox 中的工作方式:

div {
  display: flex;
  flex-direction: column-reverse;
  height: 100vh;
}

p {
  flex: 1;
}


/* demo styles */
p {
  margin: 0;
  background-color: lightgreen;
}
p + p {
  margin-bottom: 10px;
}
body {
  margin: 0;
}
<div>
  <p>Last item</p>
  <p>Second last item</p>
  <p>Top item</p>
</div>

【讨论】:

    猜你喜欢
    • 2021-05-30
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2013-05-26
    • 1970-01-01
    • 2021-10-23
    • 2010-09-28
    相关资源
    最近更新 更多