1

I've just started learning about CSS Grids and I'm struggling to achieve a certain layout. I have a grid with 4 columns and I want the total width of column 1 + column 2 to equal 50% of the grid and the total width of column 3 + column 4 to equal 50% of the grid. The tricky part is I need the individual columns to have variable widths, specifically columns 1 and 3 to expand with the text they contain and columns 2 and 4 to grow and shrink in relation to the width of columns 1 and 3. Is this possible using the grid layout?

I've been using codepen to test: https://codepen.io/anon/pen/MqxJNW

<div class="outergrid">
<div class="one">One</div>
<div class="two">Two </div>  
<div class="three">Three</div>
<div class="four">Four</div>   
<div class="five">Five</div>
<div class="six">Six</div>    
<div class="Seven">Seven</div>
<div class="Eight">Eight</div>  
<div class="Nine">Nine</div>
<div class="Ten">Ten</div>    

* {box-sizing: border-box;}
.outergrid 
{
  display:grid;
  max-width: 540px;
  margin: 0 auto;
  grid-template-columns: repeat(4, auto);
  grid-template-rows: repeat(3, auto);
  gap: 5px 5px;
}
.outergrid > div 
{
  border: 2px solid rgb(233,171,88);
  border-radius: 5px;
  background-color: rgba(233,171,88,.5);
  padding: 1em;
  color: #d9480f;
  word-break: break-word;
}

Thanks

Ant20
  • 87
  • 10
  • I don't think it's possible with Grid alone using your existing HTML structure. You need something to confine each pair of columns to 50%. Then the individual columns can freely re-size within that confined area. This would require something like a larger grid or flex container set to 50/50. Of course, that would then disrupt the flow of individual items across the nested grid. So I don't think it's possible. – Michael Benjamin Sep 21 '18 at 15:45
  • 1
    Thanks for your help @Michael_B. I suspected it might come to having multiple layers of containers but my difficulty is the the rows and columns need to align and that becomes tricky if I'm having to nest grids. The number of columns is actually dynamic so I think I'm going to have to calculate column widths. What I essentially needs is css subgrid! – Ant20 Sep 24 '18 at 07:21
  • Yes, a subgrid feature would be ideal in this case. It's out there, just not implemented in browsers yet. https://stackoverflow.com/q/47929369/3597276 – Michael Benjamin Sep 24 '18 at 10:50

0 Answers0