【问题标题】:How is "grid-template-rows: auto auto 1fr auto" interpreted?如何解释“grid-template-rows: auto auto 1fr auto”?
【发布时间】:2018-08-15 04:18:43
【问题描述】:

最近,我使用CSS grid 创建了一个布局。虽然这很好用,但我对它的工作原理感到困惑。具体来说,我对grid-template-rows: auto auto 1fr auto; 这一行感到困惑。

这里最终发生的是页眉和页脚根据内容调整大小,这是有道理的,因为它们跨越了页面的宽度。文章本身的大小根据其内容而定。但是,"title" 和 "nav" 被拆分,这样标题的大小根据内容和 nav 占据了其余的空间。

如果我改用 grid-template-rows: auto auto auto auto;,标题和导航将共享相等的间距,这不是我想要的。

auto auto 1fr auto 是如何解释的,它给了我这样的大小,使得 title 占据了所需的最小空间,而 nav 占据了其余的空间?在这种情况下,“fr”和“auto”如何交互?

main {
    display: grid;
    grid-template-columns: 10rem auto;
    grid-template-rows: auto auto 1fr auto;
    grid-template-areas: "header header" "title article" "nav article" "footer footer";
}
    
header {
  grid-area: header;
  background: lightblue;
}

div {
  grid-area: title;
  background: orange;
}

nav {
  grid-area: nav;
  background: pink;
}

article {
  grid-area: article;
  background: yellow;
}
  
footer {
  grid-area: footer;
  background: lightblue;
}
<main>
<header>This is the header</header>
<div>This is the title</div>
<nav>This is the nav</nav>
<article>
  This is the article. This is the article. This is the article. This is the article.
  This is the article. This is the article. This is the article. This is the article.
  This is the article. This is the article. This is the article. This is the article.
  This is the article. This is the article. This is the article. This is the article.
  This is the article. This is the article. This is the article. This is the article.
  This is the article. This is the article. This is the article. This is the article.
</article>
<footer>This is the footer</footer>
</main>

【问题讨论】:

  • 您的网格中有 4 行 - 所有(第 3 行除外)都是 auto 大小的。所以第一、第二和第四行auto-sized 和第三行(包含nav)占据了所有剩余空间。尝试设置grid-template-rows: auto 1fr 2fr auto; 看看会发生什么。

标签: css grid-layout css-grid


【解决方案1】:

作为一个经验法则,

  • fr 很贪心,
  • auto 很害羞。

当浏览器渲染你的网格时,首先它会计算auto元素的必要尺寸——它们都得到了它们可以承受的最小值——然后然后,在知道所有其他尺寸之后,它是否会开始用fr-proportions 填充剩余的空白。 (所以在剩下的完成后,浏览器会计算所有fr数字的总和,假设你有1fr + 1fr + 3fr + 2fr所以它是7,那么剩余的空间将被切成7等份,然后每个人都得到他们的份额。)

另外,当你分割水平空间时:

  • 1fr 1fr 1fr 会给你 3 个相等的列,
  • auto auto auto 提供自适应宽度列

【讨论】:

    【解决方案2】:

    对于 CSS 网格布局,grid-template-rowsauto 表示:

    行的大小取决于容器的大小,以及行中项目内容的大小

    1fr 是 GRID css 中的一个新的灵活单元。 [Fr] 是小数单位,1fr 是可用空间的一部分。

    这就是为什么您的第三个网格项占用了剩余空间,而所有剩余的网格项都根据其内容占用了空间

    【讨论】:

      【解决方案3】:

      1fr 表示“占用可用空间的 1 分之一”,由于没有其他元素定义为 fr,因此也表示“占用所有可用空间”

      auto 表示“取grid-auto-rows 属性具有的任何值”,默认情况下也是auto,在这种情况下意味着根据内容调整大小......但如果需要,轨道也可以拉伸要匹配其他列内容的大小

      【讨论】:

        【解决方案4】:

        【讨论】:

          猜你喜欢
          • 2020-10-01
          • 1970-01-01
          • 2020-05-21
          • 1970-01-01
          • 1970-01-01
          • 2021-09-23
          • 2017-02-28
          • 1970-01-01
          相关资源
          最近更新 更多