CSS grid: fr 和百分比单位的区别

CSS Grid: fr and percentage unit difference

我在看这个问题: 并了解到 fr 在容器中免费工作 space。我尝试检查它导致混淆。

在这个 pen 中,%fr 的行为完全相同。

在如下代码中:

main {
    width: 1000px;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    // grid-template-columns: repeat(3, 33%);
}

我的印象是:

  1. 如果您尝试 33%,无论每个网格项目的内容长度如何,容器都会分成 3 个相等的部分(按预期工作。)
  2. 如果您尝试 1fr,每个网格项目将获得 完全相同的免费 space 部分(在本例中除以三)在容器宽度的内容长度之后。即,中间会得到更多space,因为它会从左右两部分得到部分。

但在每种情况下,我得到的都是相同的宽度。为什么?

https://codepen.io/asim-coder/pen/JMdPoR

它们相同的原因是因为您没有对任何列使用任何 static 值,并且仅使用百分比和 fr。如果您使用宽度为 100px 的列,结果会有所不同,因为 33% 将保持 33%,但 1fr 将用完 all 的免费 space (在本例中为 66%-100px)。

main {
  width: 900px;
  display: grid;
  grid-template-columns: 1fr 33% 100px;
  // grid-template-columns: repeat(3, 33%);
}

// Styles for fun
// -------------------------------------------------
@import url('https://fonts.googleapis.com/css?family=Scope+One|Open+Sans:700');
body {
  background: #fff;
  color: rgb(113, 115, 136);
  font-family: 'Scope One', sans-serif;
  font-size: 1rem;
  line-height: 1;
  margin: 1rem;
}

main {
  background: #444;
  border: 3px solid #444;
  grid-gap: 3px;
}

div {
  background: #fff;
  padding: 1.5vw 2vw;
}

h1,
h2 {
  margin: 0;
}

h1 {
  color: rgb(113, 115, 136);
  font-size: 1.5rem;
  font-weight: 700;
  padding-top: .5rem;
}
<main>
  <div>1fr (longer, width is 66%-200px)</div>
  <div>
    33% (shorter, width is 33%)
  </div>
  <div>100px</div>
</main>

另一件需要注意的事情是 fr 不限于加起来等于 100。如果您的百分比值超过 100,则一切都无法正常进行。另一方面,使用 fr 可以任意组合。

main {
  width: 900px;
  display: grid;
  grid-template-columns: 33% 33% 66%;
  // grid-template-columns: repeat(3, 33%);
}

main.another {
  width: 900px;
  display: grid;
  grid-template-columns: 1fr 1fr 2fr;
  // grid-template-columns: repeat(3, 33%);
}

// Styles for fun
// -------------------------------------------------
@import url('https://fonts.googleapis.com/css?family=Scope+One|Open+Sans:700');
body {
  background: #fff;
  color: rgb(113, 115, 136);
  font-family: 'Scope One', sans-serif;
  font-size: 1rem;
  line-height: 1;
  margin: 1rem;
}

main {
  background: #444;
  border: 3px solid #444;
  grid-gap: 3px;
}

div {
  background: #fff;
  padding: 1.5vw 2vw;
}

h1,
h2 {
  margin: 0;
}

h1 {
  color: rgb(113, 115, 136);
  font-size: 1.5rem;
  font-weight: 700;
  padding-top: .5rem;
}
<h1>Broken</h1>

<main>
  <div>33%</div>
  <div>
    33%
  </div>
  <div>66%</div>
</main>

<h1>Works just fine</h1>

<main class="another">
  <div>1fr</div>
  <div>
    1fr
  </div>
  <div>2fr</div>
</main>