【问题标题】:CSS Grid not converting from a single column to a single row as a result of a media query由于媒体查询,CSS Grid 未从单列转换为单行
【发布时间】:2021-10-04 18:01:50
【问题描述】:
<div class="container">

  <div class="wrapper">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
  </div>

</div>


.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: red;
}

.wrapper {
  display: grid;
  grid-template-columns: 1fr;
  justify-items: center;
  align-items: space-around;
  min-width: 300px;
  height: 70vh;
  background: whitesmoke;
}

@media screen and (min-width: 1100px) {
  .container {
    height: auto;
    display: grid;
    grid-template-columns: 1fr repeat(2, minmax(auto, 30rem)) 1fr;
    background: pink;
  }

  .wrapper {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-column: 2/4;
    justify-content: center;
    background: cyan;
  }
}

我创建了一个包含三个圆圈的列,每个圆圈在一个列中堆叠在一起,当屏幕很窄时,这些圆圈看起来都很好。但是当浏览器被加宽并且我添加了一个媒体查询以了解屏幕何时超过 1100 像素时,我希望 column 的圆圈翻转成为单个 row 圆圈.

但是当我使用 CSS Grid 执行此操作时,它不起作用,两个圆圈出现在一行上,第三个圆圈出现在第二行的第一个圆圈下方。你可以在https://codepen.io/HorrieGrump/pen/ZEKxJgv看到它

如果我使用 flexbox 代替(如下所示),我可以通过换出 CSS 中的当前 .wrapper 块并将这个新块与 flexbox 一起使用来使其工作,但我想知道是否可以使用 CSS Grid 而不是 flexbox 来做到这一点。

谁能告诉我如何让媒体查询使用 CSS Grid 将列翻转为单行 - 而不必求助于 flexbox?

.wrapper {
    display: flex;
    flex-direction: row;
    grid-template-columns: repeat(2,1fr);
    justify-content: space-around;
    align-items: center;
    grid-column: 2/4;
    background: cyan;
  }

【问题讨论】:

    标签: css flexbox media-queries css-grid


    【解决方案1】:

    编辑 .wrapper 的媒体查询

      .wrapper {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        align-items: center;
        grid-column: 2/4;
        background: cyan;
      }
    

    【讨论】:

    • 五。有用的解决方案——谢谢,@rivrug。但这似乎违反直觉,至少对我来说是无知的,因为我会认为设置 grid-template-columns: 1fr repeat(2, minmax(auto, 30rem)) 1fr; 会中间一列是一个单一的、未分化的区域,三个圆圈可以很好地发挥作用。但是,正如您所指出的,看起来我需要再次将其分成 3 列以容纳 3 个圆圈。您认为最佳实践是什么——像这样使用 Grid 来分配圆圈,还是使用 flexbox?
    • 对于像这样简单的事情,我会坚持使用 flexbox。但是,如果您仍计划添加更多代码,则可以考虑使用 3x3 网格并将圆圈放在中间的行/列中。
    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 2019-10-30
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    相关资源
    最近更新 更多