user7646471
user7646471

Reputation: 372

Make grid rows optional

I created a grid template and wanted to make the first row optional (area: "t").

If it's hidden, the auto row should fill the remaining height. I tried it with minmax() css function but it doesn't work.

grid-template:
 "t t t t" minmax(0px, 40px)
 "h h h h" 40px
 "s l m r" auto
 "s f f f" 57px / 200px 100px auto 100px;

Here is a fiddle link: https://jsfiddle.net/nzaj8102/

I managed to get it working by creating two template classes. I was wondering, if I can do it differently ?

.template-with-top{
    grid-template:
      "t t t t" 40px
      "h h h h" 40px
      "s l m r" auto
      "s f f f" 57px / 200px 100px auto 100px;
 }


  .template-without-top{
    grid-template:
      "h h h h" 40px
      "s l m r" auto
      "s f f f" 57px  / 200px 100px auto 100px;
    }

  .template-without-top > div:nth-child(1) {
     display:none
   }

Here is the fiddle link: https://jsfiddle.net/hveu5bfc/

THX!

Upvotes: 4

Views: 1187

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371223

Although your minmax(0px, 40px) idea makes sense, it doesn't work because not everything in grid makes sense. The fact is that the minmax() function defaults to max, meaning that the row will be 40px tall even when there's no content inside.

Try this:

  • Instead of using minmax() on the first row (t t t t), set it to auto, so it takes the height of the content.
  • Instead of using auto on the third row (s l m r), set it to 1fr, so it will consume all extra height in the container when the first row has no content.
  • Control the height of the first row at the grid item level.

.app-grid {
  display: grid;
  height: 100vh;
  grid-template:
    "t t t t" auto
    "h h h h" 40px
    "s l m r" 1fr
    "s f f f" 57px;
}

.app-grid > div {
  border: 1px solid blue;
  border-radius: 5px;
}

body {
  margin: 0;
}
<div class="app-grid">
  <div style="grid-area: t; height: 40px; display: none;">t</div>
  <div style="grid-area: h;">h</div>
  <div style="grid-area: s;">s</div>
  <div style="grid-area: l;">l</div>
  <div style="grid-area: m;">m</div>
  <div style="grid-area: r;">r</div>
  <div style="grid-area: f;">f</div>
</div>

jsFiddle demo

Upvotes: 3

Related Questions