Milos
Milos

Reputation: 619

How to make grid column fit the rest of the space

I have a grid wrapper with three columns, where the first column is the biggest and it takes 2fr of width, and the second and the third columns are the same size, and they are taking both 1fr of width. What I want is to create a grid template with a dynamic number of columns, for example, if I remove one of the columns, the rest of the columns should take the remaining size equally. Here is the fiddle of what I've tried so far

.wrapper {
  display: grid;
  height: 100px;
  width: 300px;
  grid-template-columns: 2fr 1fr 1fr;
  border: 1px solid black;
}

.first {
  background-color: red;
}

.second {
  background-color: lightblue;
}

.third {
  background-color: lightgreen;
}
<div class="wrapper">
  <div class="first">
  1
  </div>
  <div class="second">
  2
  </div>
 <!-- <div class="third">
  3
  </div> -->
</div>

Fiddle

I've tried with grid-template-columns: 2fr auto auto, but that is not working well. The expected result is like this expected

but the actual result is like this

actual

Any idea how can I solve this? All examples will be appreciated!

Upvotes: 1

Views: 2676

Answers (1)

Temani Afif
Temani Afif

Reputation: 272648

Rely on implicit columns:

.wrapper {
  display: grid;
  height: 100px;
  width: 300px;
  grid-template-columns: 50%; /* one explicit column */
  grid-auto-columns:1fr; /* implicit column created when needed */
  grid-auto-flow:column;
  border: 1px solid black;
}

.first {
  background-color: red;
}

.first:last-child {
   grid-column:span 2; /* full width if alone */
}

.second {
  background-color: lightblue;
}

.third {
  background-color: lightgreen;
}
<div class="wrapper">
  <div class="first">
  1
  </div>
  <!--<div class="second">
  2
  </div>-->
 <!-- <div class="third">
  3
  </div> -->
</div>

<div class="wrapper">
  <div class="first">
  1
  </div>
  <div class="second">
  2
  </div>
 <!-- <div class="third">
  3
  </div> -->
</div>


<div class="wrapper">
  <div class="first">
  1
  </div>
  <div class="second">
  2
  </div>
 <div class="third">
  3
  </div> 
</div>

Upvotes: 2

Related Questions