Expanding cells in CSS grid layout

Viewed 334

I have the following HTML/CSS

.main {
  display: grid;
  grid-template-columns: 2fr 1fr;
}


/* The following is not essential - for decoration purposes only */

.left {
  background-color: green;
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>

Now, sometimes, and depending on the div with class main, sometimes I do not have the div with the class right (in other words, the html might look like this

.main {
  display: grid;
  grid-template-columns: 2fr 1fr;
}


/* The following is not essential - for decoration purposes only */

.left {
  background-color: green;
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
</div>

What I like to do is write the CSS code in a way that expands div.left to the full width of the container div.main if div.right does not exist. How can I do that?

2 Answers

You can rely on implicit grid creation:

.main {
  display: grid;
  grid-template-columns: 2fr;
  grid-auto-columns:1fr; /* this will trigger when you add the "right" element */
  grid-auto-flow:column;
  margin:5px;
}


.left {
  background-color: green;
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
  <div class="right">right</div>
</div>

<div class="main">
  <div class="left">Left</div>
</div>

It does also work if you want to remove left:

.main {
  display: grid;
  grid-template-columns: 2fr;
  grid-auto-columns:1fr; /* this will trigger when you add the "left" element */
  grid-auto-flow:column;
  margin:5px;
}


.left {
  background-color: green;
  grid-column-end:1; /* added this */
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
  <div class="right">right</div>
</div>

<div class="main">
  <div class="right">right</div>
</div>

This is something better suited to flexbox but if your structure is as simplistic as you indicate the only-child can be used here.

.main {
  display: grid;
  grid-template-columns: 2fr 1fr;
  margin-bottom: 1em;
}


/* The following is not essential - for decoration purposes only */

.left {
  background-color: green;
  height: 25vh;
}

.left:only-child {
  grid-column: 1 / -1;
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>

<div class="main">
  <div class="left">Left</div>
</div>

Related