Does CSS Grid have a flex-grow function?

喜夏-厌秋 提交于 2019-11-28 12:00:29

CSS Grid offers the fr unit, which functions similarly to flex-grow.

While flex-grow distributes free space in the container among flex items, the fr unit distributes free space in the container among rows / columns.

From the spec:

7.2.3. Flexible Lengths: the fr unit

A flexible length or <flex> is a dimension with the fr unit, which represents a fraction of the free space in the grid container.

(Note that flex-grow is applied to flex items, while fr lengths are applied to grid containers.)

So in your grid, you have three rows:

  1. The first row is the header. You want the content to set its height. So its height is set to auto.

  2. The last row is the footer. You want the content to set its height. So its height is set to auto.

  3. The middle row contains the nav and main elements. You want this row to occupy all remaining vertical space. So its height is set to 1fr.

.ctnr {
  display: grid;
  grid-template-rows: auto 1fr auto;  /* key rule */
  grid-template-columns: 1fr 1fr;
  height: 100vh;
  grid-template-areas: "header header" 
                         "nav main" 
                       "footer footer";
}

header {
  grid-area: header;
  background: turquoise;
}

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

main {
  grid-area: main;
  background: orange;
}

footer {
  grid-area: footer;
  background: yellow;
}

body {
  margin: 0;
}
<div class="ctnr">
  <header>header</header>
  <nav>nav</nav>
  <main>main</main>
  <footer>footer</footer>
</div>

jsFiddle demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!