Search code examples
htmlcsscss-grid

CSS Grid - Stretch to fill remaining space


I am using CSS grid to create a simple 3 column layout like this...

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

.col1 {
background:red;
text-align:center;
}

.col2 {
background:yellow;
text-align:center;
}

.col3 {
text-align:center;
background:green;
}
<div class="container">

  <div class="col1">
    Column 1
  </div>

  <div class="col2">
    <img src="https://via.placeholder.com/150">
  </div>

  <div class="col3">
    Column 3
  </div>

</div>

I am trying to change things so that the center div is only as wide as the image it contains, then col1 and col2 stretch to fill the remaining space.

Anyone have an example they can show me?


Solution

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

    Here you go, use the auto instead of 1fr for the centered div.