CSS网格布局间隙框大小

Fre*_*rth 19 css grid

我有一个CSS网格占据100%的宽度和100%的窗口高度(body元素有display: grid;).网格具有行和列模板以及占用其分配空间100%的元素.但是,当我grid-gap向网格添加一个网格时,它会使网格对于窗口来说太大,从而强制滚动条出现.如何阻止grid-gap添加到网格的尺寸 - 类似于如何box-sizing: border-box;阻止填充添加到元素的尺寸?相反,我希望间隙缩小网格的单元格.

谢谢. 像这样

Hen*_*her 11

当你使用"fr"时,它有效.

<section>
    <article class="a">A</article>
    <article class="b">B</article>
    <article class="c">C</article>
    <article class="d">D</article>
</section>

section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-auto-flow: column;
    grid-gap: 20px;

    border: 10px solid blue;

    article {
        background-color: tomato;

        &.d {
            grid-column: 2; 
            grid-row-start: 1; 
            grid-row-end: 4;

            background-color: olive;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Nen*_*car 7

它的工作原理与box-sizing: border-box您在本演示中看到的使用和填充相同.高度设置为100vh,您可以看到,如果您删除或添加grid-gap没有滚动条,您只需要从正文中删除边距.

body {
  margin: 0;
}
.grid {
  display: grid;
  height: 100vh;
  grid-gap: 20px;
  background: #FF7D7D;
  grid-template-columns: 1fr 2fr;
}
.grid > div {
  background: black;
  color: white;
}
div.a, div.d {
  color: black;
  background: white;
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
  <div class="d">D</div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 当我在你的代码中使用`fr`单位而不是百分比时,这很有用. (7认同)