删除较小视口上的CSS网格值

时间:2018-04-26 00:21:28

标签: html css css3 css-grid

我有一个CSS网格布局,我有一些跨越多个网格轨道的网格项。

当窗口低于1024px时,我想改变布局。

在这个例子中,.grid-item-5目前跨越3个轨道,我喜欢它在1024px下这个视觉元素从'.grid-item-4开始并跨越整行 - 这很简单,因为我' d执行以下操作:

@media screen
and (max-width: 1024px) {
    .grid-item-4 {
        grid-column: 1 / 8;
        background: lightblue;
    } 
}

问题:

我究竟如何关闭初始.grid-item-5值,以便它们恢复到默认值(即第5项不会跨越任何其他网格列),因此不会破坏布局?

非常感谢,

body {
    margin: 0; padding: 0;
    width: 100%;
}

#grid-wrapper {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-template-rows: repeat(3, 10rem);
    grid-gap: 1px;
}

.grid-item {
    background: red;
}

.grid-item-1 {
  grid-column: 1 / 3;
  background: yellow;
}

.grid-item-3 {
  grid-column: 4 / 8;
  background: yellow;
}

*-- I NEED TO DITCH THIS ON SMALL SCREENS --*

.grid-item-5 {
  grid-column: 2 / 6;
  background: lightblue;
}

*-- THIS IS THEN ADDED --*

@media screen
and (max-width: 1024px) {
  .grid-item-4 {
    grid-column: 1 / 8;
    background: lightblue;
  } 
}
<main id="grid-wrapper">
  <div class="grid-item grid-item-1">1</div>
  <div class="grid-item grid-item-2">2</div>
  <div class="grid-item grid-item-3">3</div>
  <div class="grid-item grid-item-4">4</div>
  <div class="grid-item grid-item-5">5</div>
  <div class="grid-item grid-item-6">6</div>
  <div class="grid-item grid-item-7">7</div>
  <div class="grid-item grid-item-8">8</div>
  <div class="grid-item grid-item-9">9</div>
</main>

2 个答案:

答案 0 :(得分:2)

grid-column的{​​{3}}为auto

default

.grid-item-5 {
  grid-column: 2 / 6;
  background: lightblue;
}

@media screen
and (max-width: 1024px) {
  .grid-item-5 {
    grid-column: auto;
  }
}

答案 1 :(得分:1)

我希望我能正确理解你......

您可以反转媒体查询,即以最小屏幕尺寸应用更改。

因此,默认情况下,.grid-row-5仅假设一列,并且在屏幕尺寸超过1024px时,它会占用额外的列。

&#13;
&#13;
body {
  margin: 0;
  padding: 0;
  width: 100%;
}

#grid-wrapper {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(3, 10rem);
  grid-gap: 1px;
}

.grid-item {
  background: red;
}

.grid-item-1 {
  grid-column: span 2;
  background: yellow;
}

.grid-item-3 {
  grid-column: span 3;
  background: yellow;
}

.grid-item-4 {
  grid-column: 1 / -1;
  background: lightblue;
}

@media screen and (min-width: 1024px) {
  .grid-item-4 {
    grid-column: span 1;
    background: red;
  }
  .grid-item-5 {
    grid-column: 2 / 6;
    background: lightblue;
  }
}
&#13;
<main id="grid-wrapper">
  <div class="grid-item grid-item-1">1</div>
  <div class="grid-item grid-item-2">2</div>
  <div class="grid-item grid-item-3">3</div>
  <div class="grid-item grid-item-4">4</div>
  <div class="grid-item grid-item-5">5</div>
  <div class="grid-item grid-item-6">6</div>
  <div class="grid-item grid-item-7">7</div>
  <div class="grid-item grid-item-8">8</div>
  <div class="grid-item grid-item-9">9</div>
</main>
&#13;
&#13;
&#13;