How to make a column span full width when a second column is not there? (CSS Grid)

Don't define the columns explicitly with grid-template-columns.

Make the columns implicit instead and then use grid-auto-columns to define their widths.

This will allow the first column (.content) to consume all space in the row when the second column (.sidebar) doesn't exist.

.grid {
  display: grid;
  grid-auto-columns: 1fr 200px;
}

.content {
  grid-column: 1;
}

.sidebar {
  grid-column: 2;
}

.grid > * {
  border: 1px dashed red; /* demo only */
}
<p>With side bar:</p>

<div class="grid">

  <div class="content">
    <p>content</p>
  </div>
  
  <div class="sidebar">
    <p>sidebar</p>
  </div>

</div>

<p>No side bar:</p>

<div class="grid">

  <div class="content">
    <p>content</p>
  </div>
  
</div>


You can get closer by using content sizing keywords, something like:

.grid {
  display: grid;
  grid-template-columns: 1fr fit-content(200px);
}

.sidebar {
  width: 100%;
}

The fit-content keyword will look at the size of the content and act like max-content until it gets to the value you pass in.

In reality you probably wouldn't need to stick a size on sidebar as the content is likely to dictate a size of at least 200 pixels (for example) but you can play around with this.

Tags:

Css

Css Grid