CSS Grid - Stretch to fill remaining space

Viewed 2699

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?

3 Answers

Change grid-template-columns to 1fr auto 1fr - see demo below:

.container {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  /* changed */
}

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

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

.col3 {
  text-align: center;
  background: green;
}

img {
  display: block; /* remove inline element "space" below image */
}
<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>

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

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

Try below snippet.

.container {
  display:grid;
  grid-template-columns:1fr auto 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 width="300px" height="300px" src="https://via.placeholder.com/150">
  </div>

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

</div>

Related