Bjørn Fridal
Bjørn Fridal

Reputation: 131

How do I handle a dynamic number of columns in CSS grid when I need different widths?

I am trying to create a CSS grid that looks like this:

| 50 pixels | auto | 100 pixels | 100 pixels | 100 pixels | 100 pixels | 50 pixels | 50 pixels

Screenshot here: https://i.sstatic.net/Z9CGY.jpg

Right now I am defining the columns width using grid-template-columns

But I can't figure out how to make the four columns of a 100 pixels (the red ones in the screenshot) dynamically. There could be just one column here, two, three or four. If there are fewer than four columns, then the column with "auto" width should take up the extra space.

Upvotes: 2

Views: 988

Answers (2)

Jitendar
Jitendar

Reputation: 497

Try this flex based solution

        .container{
            display: flex;
            height: 150px;
            width: 100%;
            
        }
        .child-100, .child-50, .child-auto{
            flex-grow: 1;
            border: 1px solid red;
        }
        .child-100{
            flex: 0 0 100px;
        }
        .child-50{
            flex: 0 0 50px;
        }
    <div class="container" >
        <div class="child-50">child-50</div>
        <div class="child-auto">child-auto</div>
        <div class="child-100">child-100</div>
        <div class="child-100">child-100</div>
        <div class="child-100">child-100</div>
        <div class="child-100">child-100</div>
        <div class="child-50">child-50</div>
        <div class="child-50">child-50</div>
    </div>

Upvotes: 2

Armin Ayari
Armin Ayari

Reputation: 619

Try this one:

.container {
  display: grid;
  grid-template-columns: 50px 1fr auto 50px 50px
}

.subgrid {
  display: grid;
  grid-auto-columns: 100px;
  grid-auto-flow: column;
}
<div class="container">
    <div>50px</div>
    <div>auto</div>
    <div class='subgrid'>
      <div>100px</div>
      <div>100px</div>
      <div>100px</div>
    </div>
    <div>50px</div>
    <div>50px</div>
  </div>

You can see the snippet here:

https://jsbin.com/zafopivine/1/edit?html,css,output

Upvotes: 4

Related Questions