how to set a max-height for a css grid row

Viewed 567

I am trying to set a max-height of 40px to the second row of a CSS Grid.
The width of the container is unknown therefore it should be responsive.
Also the content of each box is unknown.

I tried grid-template-rows: auto minmax(0, 40px); but unfortunately it will also set a height of 40px if no second row exists.

Is there any way to use grid-template-rows and prevent the second row from growing to 40px?

Here is an example where you can see that the second row takes space although there are no grid items:

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-template-rows: auto minmax(0, 40px);
  grid-auto-rows: 15px;
  overflow: hidden;
  border: 1px solid orange;
  padding: 0;
}

li {
  list-style: none;
  padding: 10px;
  background: black;
  color: white;
}


body {
 width: 650px;
}
<h1><a href="https://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F">Colors</a></h1>

<ul>
  <li>Android green</li>
  <li>Antique brass</li>
  <li>Antique bronze</li>
  <li>Antique fuchsia</li>
  <li>Antique ruby</li>
  <li>Antique white</li>
</ul>

2 Answers

The current grid implementation for minmax is always using the larger value. (See minmax() defaulting to max)

Therefore minmax(0, 40px) will always result in 40px.

You can use the grid-auto-rows property to define the height of implicitly created grid rows.

In your case, you'll define your grid as having only one row. Then any additional grid rows created by your content will use the dimensions defined with the grid-auto-rows property. This way the second row won't exist until it's needed.

Edit: To have only one row display by default, but also define a height of 40px for a second row if needed, AND define a height of 15px for third, fourth, fifth rows if needed, you can add multiple values to grid-auto-rows.

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-template-rows: auto;
  grid-auto-rows: 40px 15px 15px 15px;
  overflow: hidden;
  border: 1px solid orange;
  padding: 0;
}
li {
  list-style: none;
  padding: 10px;
  background: black;
  color: white;
}
body {
 width: 650px;
}
<h1><a href="https://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F">Colors</a></h1>

<ul>
  <li>Android green</li>
  <li>Antique brass</li>
  <li>Antique bronze</li>
  <li>Antique fuchsia</li>
  <li>Antique ruby</li>
  <li>Antique white</li>
</ul>

Related