如何正确重置网格模板列?

Mat*_*hew 4 html css css-grid

我在CSS网格中有两列布局,想切换到1024px的单列布局。

.page {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-template-rows: auto;
  grid-column-gap: 5pt;
  grid-row-gap: 5pt;
}

@media (max-width: 1024px){
  .page{
    display: block;
  }
}
Run Code Online (Sandbox Code Playgroud)

更改显示类型是禁用grid-template-rows等的完整解决方案,还是应该明确重置?

使用网格设置显示类型时,是否有任何“陷阱”?

Mic*_*l_B 6

的初始值grid-template-columnsgrid-template-rowsnone

因此,要重置属性(意味着没有创建任何明确的轨道),您可以grid-template-columns: none在媒体查询中切换到。

您也可以切换到grid-template-columns: 1fr,使用一个明确的列创建一个网格。

article {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 100px;
  grid-column-gap: 5pt;
  grid-row-gap: 5pt;
}

section {
  background-color: green;
}

@media (max-width: 600px) {
  article {
    grid-template-columns: 1fr;
    /* OR, change value to 'none' */
  }
  section {
    background-color: orangered;
  }
}
Run Code Online (Sandbox Code Playgroud)
<article>
  <section></section>
  <section></section>
</article>
Run Code Online (Sandbox Code Playgroud)

jsFiddle演示

规格参考:

  • @Adrift,自2017年[现代浏览器实现Grid](/sf/answers/3224258061/)以来,我几乎一直在将Grid用于网站布局。网格可以轻松完成Flexbox难以完成的许多工作。对于较小和较简单的布局项目,我倾向于使用flexbox。就是说,有很多[flexbox优于网格的优势](/sf/ask/3854514191/)。 (2认同)