1

I have trouble with understanding how CSS grid rows work. Why columns expand from left to right and rows don't?

.grid {
  position: absolute;
  height: 50vh;
  width: 30vw;
  border: 1px solid black;
  top: calc(50% - 30vh);
  left: calc(50% - 15vw);
}

.keys {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
}

.keys>button {
  font-size: 30px;
  text-align: center;
  line-height: 30px;
  border: 1px solid black;
}
<div class="grid">
  <div class="keys">
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
  </div>
</div>

I would want those buttons to go all the way down without giving them specific height etc.

How to achieve that easily ?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Bartek
  • 81
  • 10
  • I think you will find that if you remove these from your CSS `height: 50vh; width: 30vw;` the width and height of the grid get adjusted to the size (number) of your elements – blurfus Mar 26 '20 at 16:44
  • With block-level elements, full width is automatic. Full height is not. https://stackoverflow.com/a/46546152/3597276 – Michael Benjamin Mar 26 '20 at 16:49

1 Answers1

0

Your <div>.keys inside your <div>.grid is not set to expand the entire grid <div> element.

You need to ensure that all divs within the grid div are set to fill the entire container in order for the children to also do so.

Adding height: 100% to your keys container will fix this.

You need to add the following code

.keys {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
  height: 100%;
}

Alternatively, you can get rid of styling in the grid all together, and move all of the CSS inside of it to the keys element. This way, you won't need to set height, like so

.keys {
  display: grid;
  position: absolute;
  height: 50vh;
  width: 30vw;
  border: 1px solid black;
  top: calc(50% - 30vh);
  left: calc(50% - 15vw);
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
}

When using fr as a dimension, it will always fill a fraction of the parent container. repeat(4, 1fr) would style the element's dimensions to 25% of the parent container, whether width or height.

IndustryDesigns
  • 1,938
  • 2
  • 12
  • 22