【问题标题】:Change layout from row to grid on screen resize在屏幕调整大小时将布局从行更改为网格
【发布时间】:2021-10-28 18:24:26
【问题描述】:

我有一个非常具体的用户体验请求。我在一个容器中有四个链接,一个在一行中彼此相邻,由一条垂直线分隔。

示例:

链接一 |链接二 |链接三 |链接四

如果它们都适合容器,这就是布局。一旦用户减小屏幕尺寸并且链接不再适合,我想将布局切换为 2 行和 2 列。并在行之间有一个水平分隔线。 此外,链接的存在是可变的。如果只有三个链接,则第三个链接将延伸到整个底行。

示例:

链接一 |链接二


链接三 |链接四

或者

链接一 |链接二


链接三

如果可能的话,我想在不使用 JS 的情况下实现这种行为。理想情况下使用 Flexbox 或 Bootstrap。 有可能吗?

【问题讨论】:

标签: html css bootstrap-4 flexbox window-resize


【解决方案1】:

您可以尝试使用网格和媒体查询:

.container {
   display: grid;
   grid-template-columns: repeat(4, 1fr);
   text-align: center;
   margin: 1em;
}
a {
  border-right: 1px solid grey;
}
a:last-child {
   border-right: none;
}
@media screen and (max-width: 500px) {
 .container {
    grid-template-columns: repeat(2, 1fr);
  }
  .container a:nth-child(1), a:nth-child(2) {
    border-bottom: 1px solid grey;
  }
  a:nth-child(2) {
    border-right: none;
  }
  a:nth-child(3):last-child {
    grid-column: 1/3;
  }
}
<div class="container">
  <a>Link 1</a>
  <a>Link 2</a>
  <a>Link 3</a>
  <a>Link 4</a>
</div>

<div class="container">
  <a>Link 1</a>
  <a>Link 2</a>
  <a>Link 3</a>
</div>

【讨论】:

  • 太棒了。如果只有 3 个链接,是否还有一种方法可以使“链接 3”跨越整个底行?所以它将是 6、6、12。
  • 对不起伙计,我不知道没有 JS 是否可以做到这一点。如果我们知道会有 3 个链接,那么我们只需要在第三个链接上设置grid-column: 1/3。但是我们不知道链接的数量:(
  • 是否可以使用此处描述的兄弟姐妹数量? stackoverflow.com/questions/8720931/…
  • 非常感谢伙计,我今晚学到了一些新东西 :) 答案已更正,请看一下 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 2020-11-29
相关资源
最近更新 更多