Search code examples
htmlcsscss-grid

Why children in css grid are taking 100% horizontally but only 90% vertically of their container?


I don´t understand why horizontally everthing seems perfect but vertically as you can see in the image, there´s no margin. If this worked for the grid to take the whole width:

 grid-template-columns: repeat(3, 30%);

Why this didn´t work for taking the whole height?:

grid-template-rows: repeat(3, 30%);

enter image description here

This is the code: The .box is the container and the .card are the childs:

.box{
  /*
    margin: 20vh auto;
    text-align: center;
    width: 75%;
    max-width: 650px;
    height: 60vh;
*/
    display: grid;
    grid-template-columns: repeat(3, 30%);
    grid-template-rows: repeat(3, 30%);
    grid-gap: 12px;
    justify-content: center;
}

.card{
    border: 2px solid gray;
    height: 100%;
    border-radius: 6px;
}
<div className="box">
            <Card />
            <Card />
            <Card />

            <Card />
            <Card />
            <Card />

            <Card />
            <Card />
            <Card />
        </div>


Solution

  • You need to set a height on the container with the class of box and use fr as a unit instead of percent. You need the container height so the grid cells can calculate their height from it. If you use fr instead of percent the grid gaps are first subtracted from the container width/height before the remaining space is being divided according to the settings for grid-template-columns and grid-template-rows. Here is a working example:

    <div class="box">
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>
    
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>
    
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>
    </div>
    
    body {
      margin: 0;
    }
    
    .box {
        background-color: hotpink;
        height: 100vh;
        width: 100vw;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-template-rows: repeat(3, 1fr);
        grid-gap: 12px;
    }
    
    .card{
        border: 10px solid gray; // even with 10px or more nothing exceeds the container boundaries any more
        //height: 100%; // you do not need this, since the height is being calculated as a fr of the container height
        //box-sizing: border-box; // if you decide to set a height nonetheless you have to change box-sizing so the borders are not taking up extra space
        background-color: skyblue;
        border-radius: 6px;
    }