Can I set css grid row height based on if anything targets it with grid-area?

Viewed 63

Is it possible to set a css grid row height based on if the grid area is being used?

.container {

  height: 100vh;

  grid-template-areas: 
    "mobile-head mobile-head mobile-head" 
    "nav app app"
    "footer footer footer";
}

.nav {
  grid-area: nav
}
 <div class="container">
   <div class="nav">Nav stuff</div>
 </div>

Given the above grid template and html, I see the Nav stuff in the nav area, but naturally the mobile nav area is taking a 1/3rd of the screen height. Because there is no div that has a grid-area: mobile-head I want the height to be 0px.

But if I change the .nav to

...
  .nav {
    grid-area: mobile-head 
}

I would want the row to be a fixed height of say 200px.

I can get close. I can get the row to have a height of 0 when there is nothing in the mobile-area by doing this:

  ...
  grid-template-rows: minmax(0px, auto) 1fr 1fr

But then the height is dictated by the content, rather than the grid.

I'm fairly sure the only alternative to achieve what im trying to do is to use 2 grids, and media queries. (I want to place the nav on the left for desktop, or top if mobile)

1 Answers

I think grid-auto-rows: min-content is what you're after.

<button class="toggle" style="margin-bottom:1em">Toggle hidden row</button>
<div class="container">
   <div class="nav">Nav stuff</div>
</div>
<style>
.container {
  box-shadow: inset 0 0 0 1px lightgray;
  background-color: #fafafb;
  display: grid;
  height: 100vh;
  grid-auto-rows: min-content;
  grid-template-areas: 
    "mobile-head mobile-head mobile-head" 
    "nav app app"
    "footer footer footer";
}

.nav {
  grid-area: nav;
  background-color: lightblue;
}
.nav.mobile {
  grid-area: mobile-head;
}
</style>
<script>
document.querySelector('.toggle').onclick = function(){
  document.querySelector('.nav').classList.toggle('mobile');
};
</script>

Related