如何解释“ grid-template-rows:auto auto 1fr auto”?

7 css css3 grid-layout css-grid

最近,我使用CSS grid创建了一个布局。尽管效果很好,但我对它的工作方式感到困惑。具体来说,我对这条线感到困惑grid-template-rows: auto auto 1fr auto;

最终发生的是页眉和页脚根据内容确定大小,这很有意义,因为它们跨越了页面的宽度。文章本身的大小取决于其内容。但是,“标题”和“导航”被拆分,以使标题根据内容的大小确定,并且导航占用了其余空间。

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

如何auto auto 1fr auto解释它,以便给我确定大小,使标题占据最小的空间,而导航则占据其余空间?在这种情况下,“ 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

dke*_*ner 21

作为一个经验法则,

  • fr 很贪心,
  • auto 害羞。

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

此外,当您拆分水平空间时:

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


Bhu*_*wan 11

对于 CSS 网格布局,该grid-template-rowsauto意味着:

行的大小由容器的大小决定,并取决于行中项目内容的大小

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

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