为什么网格项不居中?

Why are grid items not centered?

出于某种原因,两个输入范围使网格中的前两项偏离中心。

我假设这是因为它们的阴影 DOM 样式。真的是这样吗?

有人知道为什么范围会使项目 A 和 B 偏离中心吗?

Here is a codepen.

body { margin: 0; background: #0d0d0d; }

#center{width:2px;height:100%;position:absolute;left:calc(50% - 1px);background:red;}

#grid {
  width: 80%;
  height: 30%;
  position: absolute;
  top: 35%;
  left: 10%;
  display: grid;
  grid-template-areas:
    "a a b b"
    "c c c d"
    "e e e f"
    "g g g g"
    ;
  grid-gap: 10px;
  color: #fff;
  box-sizing: border-box;
  border: dotted yellow 1px;
}

#a, #b { display: flex; justify-content: center; align-items: center; }

#a, #b, #d, #f, #g { background: #1a1a1a; }

#a { grid-area: a; }
#b { grid-area: b; }
#c { grid-area: c; }
#d { grid-area: d; }
#e { grid-area: e; }
#f { grid-area: f; }
#g { grid-area: g; }
<div id="center"></div>
<div id="grid">
  <div id="a">A</div>
  <div id="b">B</div>
  <input type="range" id="c">
  <div id="d"></div>
  <input type="range" id="e">
  <div id="f"></div>
  <div id="g">&nbsp;</div>
</div>

问题

当您不使用 grid-template-columns(对于显式网格)或 grid-auto-columns(对于隐式网格)定义网格列宽时,每列的宽度留给 auto.这意味着宽度由内容决定。

您已使用 grid-template-areas 定义布局:

grid-template-areas:  "a a b b"
                      "c c c d"
                      "e e e f"
                      "g g g g" ;

但是您还没有定义列,所以它们留给了它们自己的设备。

在这种情况下,auto 列会导致网格中的视觉(但不是实际)错位:

如Chrome所示:


解决方案

由于您使用的是四列隐式网格,因此您可以将此规则添加到网格容器中以解决问题。

grid-auto-columns: 1fr

现在,容器不再根据内容大小分配 space,而是在列之间均匀分配 space。

Chrome,加上上面的调整:

revised codepen

您也可以使用此规则解决问题:

grid-template-columns: repeat(4, 1fr);

revised codepen


浏览器变体

顺便说一句,您的布局在支持网格的浏览器中呈现不同。

Chrome

Firefox

边缘

(我没有在 Safari 中测试。)

基本上,在 Firefox 和 Edge 中,范围输入看起来像是锁定在第一列并且不遵守 grid-template-areas 规则。

这是因为这些浏览器对此类输入设置了默认设置:

Firefox

所以基本上这些输入设置为width: 12em

要解决此问题,请将此添加到您的代码中:

input { width: auto }

现在一切都应该适用于所有支持网格的浏览器。

revised codepen

body { margin: 0; background: #0d0d0d; }

#center{width:2px;height:100%;position:absolute;left:calc(50% - 1px);background:red;}

#grid {
  width: 80%;
  height: 30%;
  position: absolute;
  top: 35%;
  left: 10%;
  display: grid;
  grid-template-areas:
    "a a b b"
    "c c c d"
    "e e e f"
    "g g g g"
    ;
  grid-gap: 10px;
  color: #fff;
  box-sizing: border-box;
  border: dotted yellow 1px;
  grid-auto-columns: 1fr; /* NEW */
}
input { width: auto; } /* NEW */

#a, #b { display: flex; justify-content: center; align-items: center; }

#a, #b, #d, #f, #g { background: #1a1a1a; }

#a { grid-area: a; }
#b { grid-area: b; }
#c { grid-area: c; }
#d { grid-area: d; }
#e { grid-area: e; }
#f { grid-area: f; }
#g { grid-area: g; }
<div id="center"></div>
<div id="grid">
  <div id="a">A</div>
  <div id="b">B</div>
  <input type="range" id="c">
  <div id="d"></div>
  <input type="range" id="e">
  <div id="f"></div>
  <div id="g">&nbsp;</div>
</div>