How to avoid CSS grid stretching rows?

Viewed 3928

The code below is (partially) very hacky, but it shows what I'd like to achieve: the nav element's (auto) height matches its content, while aside is stretched all the way down (along with main).

But if I remove the two hacky grid-row declarations (with span 998/999), nav is stretched, so nav and aside have the same height, which I don't want.

Which would be a clean way to achieve the desired result?

div {
  display: grid;
  grid-template-columns: 60% 40%;
  grid-template-areas: "main nav" "main aside";
  text-align: center;
}

main {
  grid-area: main;
  background: silver;
  line-height: 8;
  grid-row: 1 / span 999;
}

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

aside {
  grid-area: aside;
  background: lightgray;
  grid-row: 2 / span 998;
}
<div>

  <nav>nav: just a few links</nav>
  <main>main:<br>very<br>long<br>content</main>
  <aside>aside: short content</aside>

</div>

1 Answers

You can optimize your code like below. The trick is the use of grid-template-rows:auto 1fr;

div {
  display: grid;
  grid-template-columns: 60% 40%;
  grid-template-rows:auto 1fr;
  grid-auto-flow:dense;
  text-align: center;
}

main {
  background: silver;
  line-height: 8;
  grid-row:span 2;
}

nav {
  background: grey;
  grid-column: 2;
}

aside {
  background: lightgray;
}
<div>

  <nav>nav: just a few links</nav>
  <main>main:<br>very<br>long<br>content</main>
  <aside>aside: short content</aside>

</div>

Related