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>

Leave a Comment