Search code examples
csscss-grid

Defining columns for a variable number of items, all in one row, equally spaced


I am having a hard time describing what I am looking for (searching on Google)

I have dynamic logo content, it could be 3 logos, it could be 7.. My template needs to accommodate them all, They all need to display in one row equally spaced..

So for example if I knew in advance I had 3 items my code would be this

grid-template-columns: 1fr 1fr 1fr; 

if I knew in advance I had 7 items my code would be this

grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr; 

I won't know how many items I have ever. So how can I code this to accommodate a dynamic amount of columns?


Solution

  • This configuration is suitable for Flexbox where all you need to do is

    .wrapper {
      display:flex
    }
    .wrapper img {
      flex:1;
    }
    

    Using CSS grid you have to do

    .wrapper {
      display:grid;
      grid-auto-columns:1fr;
      grid-auto-flow:column;
    }
    

    You consider a column flow and you define the width of column to be equal to 1fr

    .wrapper {
      display:grid;
      grid-auto-columns:1fr;
      grid-auto-flow:column;
      grid-gap:5px;
      margin:10px;
    }
    
    .wrapper span {
      height:50px;
      background:red;
    }
    <div class="wrapper">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
    </div>
    
    <div class="wrapper">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
    </div>