首页 > 解决方案 > 如何设置网格模板行/列的属性,以便在没有足够元素的情况下保持居中?

问题描述

就我而言,这将是关于网格模板列的,也就是说我假设相同的逻辑将适用于网格模板行。

这里是演示:https ://stackblitz.com/edit/react-rvxhzc?file=style.scss

您将看到右侧网格元素的剩余空间比左侧网格元素大。这种情况重现了我在代码中遇到的一个问题,其中卡片的布局以两个剩余元素而不是其他行上的三个元素结束。我考虑过一个属性,它将网格模板设置为“grid-template-columns:repeat(max-repeat(3), auto)”,与 max-width 允许我们限制宽度并仍然定义的风格相同同时宽度的范围。

如果最后一行没有足够的元素来完全填充它,如何确保网格的元素保持居中?

这里是 ReactJS 的片段:

 <div className="component">
      <p className="component__introducing-text"> if you look attentively you will see the space is different on the two elements' sides</p>
        <div className="component__grid">
          <div className="component__grid-first-element">
            div 1
          </div>
          <div className="component__grid-second-element">
            div 2
          </div>
        </div>
      </div>

这里是编译后的 Sass 片段:

.component__grid-second-element, .component__grid-first-element, .component__introducing-text {
  display: flex;
  justify-content: center;
  align-items: center;
}

.component__grid-second-element, .component__grid-first-element {
  height: 40vh;
  width: 25vw;
}

.component__introducing-text {
  margin: 10vh auto 0;
}

.component__grid {
  width: calc(100vw - (100vw - 100%));
  margin-top: 8vh;
  display: grid;
  grid-template-columns: repeat(3, auto);
  justify-content: center;
  align-items: center;
  grid-column-gap: 5.5vw;
}

.component__grid-first-element {
  background: pink;
}

.component__grid-second-element {
  background: green;
}

标签: htmlcss

解决方案


推荐阅读