Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a height value on an individual CSS Grid row

Tags:

css

css-grid

I have a CSS grid layout where I have the top row spanning the entire grid using the grid-column property.

Does anyone know how I can set this row to be 100px high and have all the subsequent rows set to a grid-auto-rows height of 200px?

I know I can input individual values with grid-template-rows for all the specific rows, but there are going to be a lot of divs on the page and don't want to input 100px and then a load of 200px values using this grid-template-rows property.

I'm thinking there must be a way to set individual pixel values on certain rows and then have everything else as grid-auto-rows?

I can't seem to find how to do this in the docs.

Any help would be awesome!

https://codepen.io/emilychews/pen/dZPJGQ

.gridwrapper {
  display: grid;
  grid-template-columns: repeat(2, 2fr);
  grid-auto-rows: 200px;
  grid-template-rows: 100px 200px;
  grid-gap: 10px;
}

nav {
  background: yellow;
}

.gridwrapper div {
  padding: 1em;
  background: red;
  color: white;
  box-sizing: border-box;
}

.gridwrapper div:nth-child(odd) {
  background: blue;
}

nav {
  grid-column: 1 / -1;
}

/*MAKE DIVS 1FR ON MOBILE*/
@media only screen and (max-width: 736px) {
  .gridwrapper {
    grid-template-columns: 1fr;
  }
}
<div class="gridwrapper">
  <nav class="grid">1</nav>
  <div class="grid">2</div>
  <div class="grid">3</div>
  <div class="grid">4</div>
  <div class="grid">5</div>
  <div class="grid">6</div>
</div>
like image 311
pjk_ok Avatar asked Oct 30 '17 14:10

pjk_ok


1 Answers

Does anyone know how I can set this row to be 100px high and have all the subsequent rows set to a grid-auto-rows height of 200px?

Yes. Grid can do this cleanly and easily.

First, you don't need to set a height value on the grid item itself. That overrides one of the great benefits of CSS Grid: the ability to control the dimensions of grid items at the container level.

You know that your grid will always have at least one row: the top row. That's your explicit grid.

You don't know how many additional rows there will be. That number is variable and unpredictable. That's your implicit grid.

The grid-template-rows and grid-template-columns properties set track sizes in the explicit grid.

The grid-auto-rows and grid-auto-columns properties set track sizes in the implicit grid.

Therefore, this is probably what you're looking for:

.gridwrapper{
    display: grid;
    grid-template-rows: 100px; /* top row is 100px in height */
    grid-auto-rows: 200px;     /* any new rows created are 200px in height */
}

revised codepen

like image 157
Michael Benjamin Avatar answered Sep 27 '22 19:09

Michael Benjamin