首页 > 解决方案 > 具有独立水平移动容器的响应方块网格

问题描述

我正在尝试制作一个覆盖整个视口的响应方块/容器网格,并且每行独立水平滑动。在横向有 4 行,其中 1 行是 25vh 高,所以它们一起显然覆盖了 100% 的视口高度。它应该是一个适应触摸屏的界面。

这是一个代码示例:

<div>
  <div className="group-1">
    <Square 1.1 />
    <Square 1.2 />
    <Square 1.3 />
    <Square 1.4 />
    <Square 1.5 />
  </div>
  <div className="group-2">
    <Square 2.1 />
    <Square 2.2 />
    <Square 2.3 />
    <Square 2.4 />
    <Square 2.5 />
  </div>
  <div className="group-3">
    <Square 3.1 />
    <Square 3.2 />
    <Square 3.3 />
    <Square 3.4 />
    <Square 3.5 />
  </div>
  <div className="group-4">
    <Square 4.1 />
    <Square 4.2 />
    <Square 4.3 />
    <Square 4.4 />
    <Square 4.5 />
  </div>

还有 .css 文件(我意识到这是做正方形的一种糟糕方法,我无法让它以任何其他方式工作):

.group*>Square* {
  width: 25vh;
  height: 25vh;
}

@media (hover: none) and (pointer: coarse) {
  .group* {
    overflow-x: auto;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    scroll-snap-type: x mandatory; 
    scrollbar-width: none;
    margin-bottom: 0;
    padding-bottom: 0;
  };
}

.group*::-webkit-scrollbar {
  display: none;
}

上面的解决方案在横向上效果很好,默认情况下屏幕上也有足够的正方形可见。在纵向也有 4 行,正方形更大,屏幕上的数量更少(显然):

这个解决方案并不漂亮,因为当我添加新方块时,我必须手动完成并决定将它们添加到哪个组。我试图将一大排正方形包裹成四个,但我无法让每一行彼此独立地水平移动。

我想做的事?

我想在横向方向有 4 行正方形,在纵向方向有 5 行。我想通过水平独立滑动行来保持此功能。我对 CSS 很陌生,我不知道如何让它工作。纯CSS有办法吗?

标签: htmlcssreactjsresponsive-designcss-grid

解决方案


您可以使用 css 网格来完成您正在寻找的东西。我不认为这正是您想要的特定布局,但是如果您尝试一些规则,您将能够轻松地按照自己的喜好采用它。

body {
  padding: 1rem;
}

.gallery {
    display: grid;
    grid-gap: 1rem;
        grid-template-columns: repeat(2, 1fr);
        grid-auto-rows: 25vh;
    height: calc(100vh - 1rem);
    margin: 0 auto;
    max-width: 1200px;
}

@media all and (min-width: 640px) {
  .gallery {
    grid-template-columns: repeat(4, 1fr);
  }
}

.gallery div {
    flex: 1 0 auto;
        height: 25vh;
    background: #1a1a1a;
}
<div class="gallery">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>


推荐阅读