Search code examples
csslayoutcss-grid

Expand CSS grid cell


Here's what I have right now:

enter image description here

.post {
  display: grid;
  gap: 2rem;
}

.post div:nth-child(1) {
  grid-area: 1 / 1;
}
.post div:nth-child(2) {
  grid-area: 1 / 2 / 1 / 2;
}
.post div:nth-child(3) {
  grid-area: 1 / 3;
}
<div class="post">
  <div class="post__id">
    <p>001</p>
  </div>
  <div class="post__body">
    <a href="..."><p>Lorem ipsum</p></a>
    <p>text…</p>
  </div>
  <div class="post__date">
    <p>01.01.2021</p>
  </div>
</div>

Is there a good way to expand the cell in the middle to take up the maximum amount of space as it is the case with the cells below filled with text?

P.S.: One way to solve this:

.post {
  display: grid;
  gap: 2rem;
  grid-template-columns: 1fr 1000fr 1fr;
}
/* and comment out the rest of the above code */

But I don't think it's a good solution…


Solution

  • Use grid-template-columns: auto 1fr auto.

    This seems a bit odd as 1fr seems to be a somewhat fixed length and auto seems to represent a dynamic length. But check out the values for grid-template-columns

    <flex>
    Is a non-negative dimension with the unit fr specifying the track's flex factor. Each <flex>-sized track takes a share of the remaining space in proportion to its flex factor.

    When appearing outside a minmax() notation, it implies an automatic minimum (i.e. minmax(auto, <flex>)).

    auto
    As a maximum represents the largest max-content size of the items in that track.

    As a minimum represents the largest minimum size of items in that track (specified by the min-width/min-height of the items). This is often, though not always, the min-content size.

    If used outside of minmax() notation, auto represents the range between the minimum and maximum described above. This behaves similarly to minmax(min-content,max-content) in most cases.

    So auto is practically just max-content and 1fr will take all the remaining space.

    .post {
      display: grid;
      gap: 2rem;
      grid-template-columns: auto 1fr auto;
    }
    
    .post div:nth-child(1) {
      grid-area: 1 / 1;
    }
    .post div:nth-child(2) {
      grid-area: 1 / 2 / 1 / 2;
    }
    .post div:nth-child(3) {
      grid-area: 1 / 3;
    }
    <div class="post">
      <div class="post__id">
        <p>001</p>
      </div>
      <div class="post__body">
        <a href="..."><p>Lorem ipsum</p></a>
        <p>text…</p>
      </div>
      <div class="post__date">
        <p>01.01.2021</p>
      </div>
    </div>