Search code examples
htmlcsscss-grid

Why isn't my grid-container positioning the grid-cells the way I want it to?


.grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, 10%);
    border: 1px solid red;
    background-color: white;
}

.grid-container > div:nth-child(1) {
    background-color: #B10DC9;
}

.grid-container > div:nth-child(2) {
    background-color: antiquewhite;
}

.grid-container > div:nth-child(3) {
    background-color: aquamarine;
}
<div class="grid-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

GC = grid-container. GI = grid-item.

So far I can add in any number of GIs into the GC and have each GI take up only 10% of the GC's width. Is there a way to make it so that for any number of GIs I add, each GI takes up an equal portion of the GC - achieving this through CSS (not javascript)? fr units did not do the trick.


Solution

  • You set 10%, which means that your divs will not creep out to the entire free width.

    But you can do it like this using minmax():

    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    

    This means that when your divs reach 100px wide, these divs will blend under each other.

    .grid-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
        border: 1px solid red;
        background-color: white;
    }
    
    .grid-container > div:nth-child(1) {
        background-color: #B10DC9;
    }
    
    .grid-container > div:nth-child(2) {
        background-color: antiquewhite;
    }
    
    .grid-container > div:nth-child(3) {
        background-color: aquamarine;
    }
    <div class="grid-container">
      <div>1</div>
      <div>2</div>
      <div>3</div>
    </div>