search

Home  >  Q&A  >  body text

CSS grid layout, automatically adding rows and setting column width to maximum grid item width

I want a grid layout with any number of grid items, and when a grid item is filled, it automatically creates a new row, kind of like:

#grid {
  display: grid;
  width: 256px;
  border: 1px solid black;
  grid-gap: 12px;
  grid-template-columns: repeat(auto-fit, minmax(75px, 1fr));
}

#grid span {
  background-color: lightgray;
}
<div id=grid>
  <span>content 1</span>
  <span>content 2</span>
  <span>content 3</span>
  <span>content 4</span>
  <span>content 5</span>
  <span>content 6</span>
  <span>content 7</span>
  <span>content 8</span>
  <span>content 9</span>
  <span>content 10</span>
</div>

The problem is that I don't want to hardcode 75px. Is there a way to set this value to the "content width of the widest grid item"?

I tried changing 75px to min-content, which seems to work per spec, but the dev tools say this is invalid CSS. I've also tried setting just grid-auto-columns: min-content instead of grid-template-columns, which seems to set the width correctly but takes up A whole row.

P粉818317410P粉818317410281 days ago476

reply all(1)I'll reply

  • P粉787820396

    P粉7878203962024-03-29 10:18:39

    The short answer is no. But it's a great question, and I think it's a common use case that really should be supported.

    You will be in Grid template columns. Auto-repeat The relevant part of is

     = 
      repeat( [ auto-fill | auto-fit ] , [ ?  ]+ ? )

    where fixed size is

     = 
                                         |
      minmax(  ,  )       |
      minmax(  ,  )

    Other bits are

     = 
        |
                     |
      min-content          |
      max-content          |
      auto                 
    
     = 
        |
      min-content          |
      max-content          |
      auto                 
        
     = 
        
    
     = 
            |
      

    This means that when using minmax() to automatically generate columns in grid-template-columns, your minimum or maximum value needs to be Fixed length or percentage. You can use max-content as the first value in a minmax expression, but only if you then use a fixed length or a percentage as the second value in the expression. Very annoying, isn't it? I wish I understood why this limitation exists.

    Can we solve this problem? Is this example closer to what you want?

    #grid {
      display: grid;
      width: 550px;
      border: 1px solid black;
      grid-gap: 1em;
      grid-template-columns: repeat(auto-fit, minmax(max-content,18%));
      overflow: hidden;
    }
    
    #grid span {
      background-color: lightgray;
    }
    content 1 content 22 content 333 content 4444 content 55555 content 666666 content 7777777 content 88888888 content 999999999

    reply
    0
  • Cancelreply