How to properly reset grid-template-columns?

Viewed 6620

I have a two column layout in CSS grid and would like to toggle to a single column layout at 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;
  }
}

Is changing the display type a complete solution for disabling grid-template-rows etc., or should they explicitly reset?

Are there any "gotchas" when setting display types using grid.

3 Answers

The initial value of grid-template-columns and grid-template-rows is none.

So to reset the properties (meaning there are no explicit tracks created), you would switch to grid-template-columns: none in your media query.

You can also switch to grid-template-columns: 1fr, which creates a grid with one explicit column.

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;
  }
}
<article>
  <section></section>
  <section></section>
</article>

jsFiddle demo

Spec reference:

Also consider using unset:

grid-template-columns: unset;

Which resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not.

So:

.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 {
    /* Here: */
    grid-template-columns: unset;
  }
}

The most simple way to reset any CSS property to its initial value is to use initial value. It will work on any property and you won't have to worry about any property defaults.

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

.item {
  height: 100px;
  background-color: green;
}

@media (max-width: 1024px) {
  .page {
    grid-template-columns: initial;
  }
}
<div class="page">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

But in the current case 1fr and none will work as well, of course.

Related