如何让网格区域有文档流?

时间:2017-11-01 19:10:30

标签: css css3 css-grid

我有一个包含两个区域(left& right)的CSS网格。我想在这些区域中放置多个span,但是当我执行以下操作时,这些项目会显示在彼此之上,就好像它们已从文档流中取出一样。

如何将它们放回文档流程中,使它们彼此相邻?

div {
    display: grid;
    grid-template: 1fr 1fr / 1fr;
    grid-template-areas: "left right"
}

div .left {
    grid-area: left;
}

div .right {
    grid-area: right;
}
<div>
    <span class="left">First</span>
    <span class="left">Second</span>
    <span class="left">Third</span>
    <span class="right">Fourth</span>
    <span class="right">Fifth</span>

</div>

Codepen

2 个答案:

答案 0 :(得分:2)

Full On Grid

网格都是关于列和行的,因此没有区域名称的版本(只是位置的别名)是:

div {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 50px 50px 50px;
}

div .left {
    grid-column: 1/1;
}

.la {
    grid-row: 1/1;
}

.lb {
    grid-row: 2/2;
}

.lc {
    grid-row: 3/3;
}

div .right {
    grid-column: 2/2;
}
<div>
    <span class="left la">First</span>
    <span class="left lb">Second</span>
    <span class="left lc">Third</span>

    <span class="right la">Fourth</span>
    <span class="right lb">Fifth</span>
</div>

两列,无论何处跨越!

如果你只想要“两列”并且不关心定位span元素,那么这对你来说可能更好。

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto;
}

.left {
    grid-column: 1/1;
    grid-row: 1/1;
}

.right {
    grid-column: 2/2;
    grid-row: 1/1;
}

span {
    display: block;
}
<div class="grid">
    <div class="left">
    <span>First</span>
    <span>Second</span>
    <span>Third</span>
    </div>

    <div class="right">
    <span>Fourth</span>
    <span>Fifth</span>
    </div>
</div>

答案 1 :(得分:1)

每个网格项必须获得唯一的grid-area名称。

如果您对多个元素应用相同的名称,那么根据级联,将显示最后一个项目,覆盖其他具有相同名称的项目。

以下是一个正确设置的示例,仅用于说明目的:

div {
  display: grid;
  grid-template-areas: "left1 right1"
                       "left2 right2"
                       "left3 right3"
                       "left4 right4"
                       "left5 right5";
}

span:nth-child(1) { grid-area: left1; }
span:nth-child(2) { grid-area: left2; }
span:nth-child(3) { grid-area: left3; }
span:nth-child(4) { grid-area: right1; }
span:nth-child(5) { grid-area: right2; }
<div>
  <span>First</span>
  <span>Second</span>
  <span>Third</span>
  <span>Fourth</span>
  <span>Fifth</span>
</div>

看来你正在寻找一个在第三排之后包裹的垂直流动网格。在这种情况下,这就是您所需要的:

div {
  display: grid;
  grid-template: repeat(3, auto) / 1fr 1fr;
  grid-auto-flow: column;
}
<div>
  <span>First</span>
  <span>Second</span>
  <span>Third</span>
  <span>Fourth</span>
  <span>Fifth</span>
</div>

在此处详细了解 grid-auto-flow: column Make grid container fill columns not rows