如何隐藏隐式网格行?

时间:2018-02-08 18:30:46

标签: html css css3 css-grid

下面的代码段使用CSS Grid来增加宽容器的列数。对于窄容器(例如,取消注释width: 80vw或调整示例大小),它会添加隐式行(grid-template-rows属性中只有2个是显式的)。如何只保留2行,使网格项“溢出”#34; 2-by-n网格隐藏?



.wrapper {
  border: 2px solid #f76707;
  background-color: #fff4e6;
  display: grid;
  /* width: 80vw; */
  grid-template-columns: repeat(auto-fill, 200px);
  grid-template-rows: repeat(2, 1fr);
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}

<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

您可以使用0px将自动生成的行的高度设置为grid-auto-rows: 0;,并使用overflow-y: hidden隐藏它们。演示:

.wrapper {
  border: 2px solid #f76707;
  background-color: #fff4e6;
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  grid-template-rows: repeat(2, 1fr);
  grid-auto-rows: 0; /* set height to 0 for autogenerated grid rows */
  overflow-y: hidden; /* hide grid items that overflow */
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
  <div>Six</div>
  <div>Seven</div>
  <div>Eight</div>
  <div>Nine</div>
  <div>Ten</div>
</div>

答案 1 :(得分:0)

您无法阻止创建隐式行(spec reference),但您可以在容器上设置高度并隐藏溢出。

&#13;
&#13;
.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  max-height: 110px;
  overflow: hidden;
  border: 2px solid #f76707;
  background-color: #fff4e6;
  
}
.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
&#13;
<div class="wrapper">
   <div>One</div>
   <div>Two</div>
   <div>Three</div>
   <div>Four</div>
   <div>Five</div>
</div>
&#13;
&#13;
&#13;

jsFiddle demo