Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set height of first row in CSS grid

I have a basic CSS grid using display: grid & I'm unable to set the height of the first row using grid-template-rows.

My HTML/CSS looks roughly like this:

.gridWrapper {
  display: grid;
  height: 100vh;
  grid-template-rows: 20px auto auto;
}

.row1 {
  grid-row-end: 1;
  background-color: lightslategray;
}

.row2 {
  grid-row-end: 2;
  background-color: lightblue;
}

.row3 {
  grid-row-end: 3;
  background-color: lightskyblue;
}

.col1 {
  grid-column-end: 1;
}

.col2 {
  grid-column-end: 2;
}
<div class="gridWrapper">
  <div class="row1 col1">Col1</div>
  <div class="row1 col2">Col2</div>
  <div class="row2 col1">A</div>
  <div class="row2 col2">B</div>
  <div class="row3 col1">D</div>
  <div class="row3 col2">D</div>
</div>

However, it results in this:

2nd row gets styled, rather than 1st

This occurs in both latest Chrome & Safari (I'm on Mac), which leads me to believe I've misunderstood something about gridlayout CSS.

How do I set the height of the first row?

like image 426
RoryD Avatar asked Nov 18 '25 06:11

RoryD


1 Answers

You're defining the grid-row-end properties, but you're using the grid-row-start lines. That's why things aren't working as you expect.

If you want .row1 elements to cover the first row, then you need them to span across the row – that means from row line 1 to row line 2.

So instead of this:

  • grid-row-end: 1

Use any of these this:

  • grid-row-start: 1
  • grid-row-end: 2
  • grid-row: 1 / 2

.gridWrapper {
  display: grid;
  height: 100vh;
  grid-template-rows: 20px auto auto;
}

.row1 {
  /* grid-row-end: 1; */
  grid-row-end: 2;  /* new */
  background-color: lightslategray;
}

.row2 {
  /* grid-row-end: 2; */
  grid-row-end: 3;  /* new */
  background-color: lightblue;
}

.row3 {
  /* grid-row-end: 3; */
  grid-row-end: 4;  /* new */
  background-color: lightskyblue;
}

.col1 {
  /* grid-column-end: 1; */
  grid-column-end: 2;  /* new */
}

.col2 {
  /* grid-column-end: 2; */
  grid-column-end: 3;  /* new */
}
<div class="gridWrapper">
  <div class="row1 col1">Col1</div>
  <div class="row1 col2">Col2</div>
  <div class="row2 col1">A</div>
  <div class="row2 col2">B</div>
  <div class="row3 col1">D</div>
  <div class="row3 col2">D</div>
</div>
like image 68
Michael Benjamin Avatar answered Nov 20 '25 10:11

Michael Benjamin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!