CSS网格项彼此堆叠而不是尊重网格区域

时间:2018-07-21 16:54:58

标签: javascript css reactjs jsx css-grid

链接到代码沙箱:https://codesandbox.io/s/rw0j2orqmp

我具有以下网格模板设置:

.calculator {
  margin: auto;
  vertical-align: center;
  width: 30%;
  height: 300px;
  background-color: blue;
  display: grid;
  grid-template-rows: repeat(5, auto);
  grid-template-columns: repeat(4, auto);
  grid-template-areas:
    "display display display display"
    "clear clear clear method"
    "number number number method"
    "number number number method"
    "number number number method"
    "posNeg number decimal method";

  #display {
    display: block;
    grid-area: display;
    margin: 5px;
    resize: none;
    text-align: right;
    font-size: 40px;
    width: 95%;
    height: 100px;
  }

  .clear {
    display: block;
    grid-area: clear;
  }

  .number {
    display: block;
    grid-area: number;
  }

  .method {
    display: block;
    grid-area: method;
  }

  .posNeg {
    display: block;
    grid-area: posNeg;
  }

  .decimal {
    display: block;
    grid-area: decimal;
  }
}

每个div中的按钮都是由React中的以下JSX生成的:

function Calculator() {
  return (
    <div className="container">
      <h1>Javascript Calculator</h1>
      <div className="calculator">
        <textarea id="display" />
        {types.map(y => (
          <div className={y} key={y}>
            {buttons.map(
              x =>
                x.type === y ? (
                  <button id={x.id} key={x.id}>
                    {x.name}
                  </button>
                ) : null
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

由于某种原因,我的div不尊重它们在网格区域中的位置,而是在设置其grid-area属性时全部呈现在底部。我尝试设置为display:block;在每个div类中,我也尝试将位置设置为父类中的几个不同值。我最初是每个按钮都自动生成的,而包装它们的div不存在,在这种情况下,每个按钮仍在底部渲染,并占据了容器元素整个底部的50%。

这是它的样子:

Items falling to bottom

1 个答案:

答案 0 :(得分:1)

这不是grid-template-areas的有效值:

grid-template-areas:
  "display display display display"
  "clear clear clear method"
  "number number number method"
  "number number number method"
  "number number number method"
  "posNeg number decimal method";

您所有的区域名称都必须在网格内形成矩形,但是number并非必须如此,例如,可以将悬垂的number更改为decimal来解决该问题:

grid-template-areas:
  "display display display display"
  "clear clear clear method"
  "number number number method"
  "number number number method"
  "number number number method"
  "posNeg decimal decimal method";