如何折叠(未删除的行)在明确声明的CSS网格布局中没有内容的行?

时间:2018-12-26 11:53:20

标签: html css css3 grid-layout css-grid

问题类似于How do you collapse unused row in a CSS grid?,但我的行已明确声明。

我有一个类似于以下设计的CSS网格:

with full content

但是,每当我没有内容/有限的内容时,我就会在其中看到一些不需要的行。我该如何删除这些行,因为这会在设计中添加不必要的空间?

我想我不能使用grid-auto-rows或其他任何东西,因为我想要那种布局,为此我需要像在CSS中那样定义行。

ref:没有足够内容时布局如何显示。

when there's not enough content

请检查代码笔:

.card {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 2fr 1fr 1fr 2fr;
  grid-gap: 5px;
}
.card * {
  /*   styles for demonstational purposes */
  background: #02750b;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px;
}
.card :nth-child(2) {
  grid-area: 1 / 2 / 3 / 3;
}
.card :nth-child(5) {
  grid-area: 3 / 2 / 5 / 3;
}
.card :nth-child(4) {
  grid-area: 2/ 1 / 4/ 2;
}
.card :nth-child(6) {
  grid-area: 2/ 3 / 4/ 4;
}

p  {
  padding: 5px;
  background: #b5b53f;
}
<div class="card">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>
<p>Some thing after the content</p>

1 个答案:

答案 0 :(得分:1)

您要在容器级别定义行。

.card {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 2fr 1fr 1fr 2fr;
  grid-gap: 5px;
}

但是内容是在网格项目级别处理的。

因此,当要求容器对显式轨道进行布局时,它会在不考虑内容存在的情况下完成该工作。

对于您而言,当内容出现或消失时,容器规则不会更改,因此没有理由使行消失。

但是我看不出任何明确的行来使这种布局有效的理由。只是把它们拿出来。

请注意,fr个单元在容器中分配了可用空间。但是您尚未在容器上设置高度,这意味着没有可用的分配空间。这可能会导致主要浏览器出现意外行为(取决于他们选择呈现这种情况的方式)。尝试在容器上设置高度,以实现更适当和更稳定的行为。

.card {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  /* grid-template-rows: 2fr 1fr 1fr 2fr; */
  grid-gap: 5px;
}
.card * {
  /*   styles for demonstational purposes */
  background: #02750b;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px;
}
.card :nth-child(2) {
  grid-area: 1 / 2 / 3 / 3;
}
.card :nth-child(5) {
  grid-area: 3 / 2 / 5 / 3;
}
.card :nth-child(4) {
  grid-area: 2/ 1 / 4/ 2;
}
.card :nth-child(6) {
  grid-area: 2/ 3 / 4/ 4;
}

p  {
  padding: 5px;
  background: #b5b53f;
}
<div class="card">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>
<p>Keep in mind you're using <i>fr</i> units in a container with no defined height. So expect free space to be distributed unevenly across examples.</p>


<div class="card">
  <div>1</div>
  <div>2</div>
  <div>3</div>
 </div>
<p>less space = smaller <i>fr</i> units = potentially shorter grid areas (browser behavior may vary)</p>