【问题标题】:CSS Grid single column layout for mobile without media queries适用于没有媒体查询的移动设备的 CSS Grid 单列布局
【发布时间】:2020-08-01 13:51:38
【问题描述】:

我的桌面屏幕的 CSS 网格布局是这样顺时针方向的:

代码:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 1px 1px;
  grid-template-areas: "one two" "four three";
}

.one { grid-area: one; }

.two { grid-area: two; }

.three { grid-area: three; }

.four { grid-area: four; }
<div class="grid-container">
  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>
  <div class="four"></div>
</div>

对于移动设备和平板电脑屏幕,我希望这些部分按递增顺序堆叠:

This: 1 | Not this: 1
      2 |           2
      3 |           4
      4 |           3

这可以在不使用媒体查询的情况下完成吗?我觉得我错过了一些简单的东西。

编辑:从目前的答案看来,我们必须使用媒体查询来处理这样的事情。接受第一个答案。

【问题讨论】:

  • 为什么你不想使用媒体查询?有什么具体原因吗?
  • @SMAKSS 没有特别的原因。我在我的项目中只对这个布局使用媒体查询,所以我想也许有办法不使用它。

标签: css css-grid


【解决方案1】:

不,你必须使用媒体查询

.grid-container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-areas: "one" "two" "three" "four";
}

【讨论】:

  • 它们会自动堆叠在一起。您可以为桌面定义媒体查询,然后将该布局应用到网格区域
  • 我已经为此使用了媒体查询,但我不擅长网格,所以我想我可能忽略了一些非媒体查询方式来做到这一点。
【解决方案2】:

好吧,AFAIK,无论如何,如果您想针对不同屏幕尺寸的设备更改布局,您应该使用媒体查询无论如何,以指示每种屏幕尺寸应出现的布局域。

所以有了这个假设,你的代码应该是这样的:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-gap: 1px 1px;
  grid-template-areas: "one two" "four three";
}

@media (max-width: 767px) {
  .grid-container {
    grid-template-columns: 1fr;
    /* If you intend to use 1fr for each column indicating grid-template-columns is not required */
    grid-template-areas: "one" "two" "three" "four";
  }
}

.one {
  grid-area: one;
}

.two {
  grid-area: two;
}

.three {
  grid-area: three;
}

.four {
  grid-area: four;
}
<div class="grid-container">
  <div class="one">1</div>
  <div class="two">2</div>
  <div class="three">3</div>
  <div class="four">4</div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2014-11-22
    • 2017-01-05
    相关资源
    最近更新 更多