3

I've got a css grid layout that is two columns and two rows:

"header header" "left right"

So header is always full 100% and left and right need to share their row evenly.

There's also a possibility of "left" not getting rendered. What I'm trying to do is have "right" fill up the entire row when it's alone.

.grid {
  display: grid;
  grid-template: 
          "header header" 
          "left right";
  grid-template-columns: 1fr 1fr;
  margin-bottom: 50px;
}

header {
  grid-area: header;
  background: #0098db;
}

.left-stuff {
  grid-area: left;
  background: #ffadad;
}

.right-stuff {
  grid-area: right;
  background: #73d073;
}
<!-- example with header and two columns -->
<div class="grid">
  <header>
    <h1>I'm the header</h1>
  </header>
  <div class="left-stuff">I'm the left stuff</div>
  <div class="right-stuff">I'm the right stuff</div>
</div>

<!-- example with header and one column -->
<div class="grid">
  <header>
    <h1>I'm the header</h1>
  </header>
  <div class="right-stuff">I'm the right stuff</div>
</div>

I tried the following:

grid-template-columns: auto 1fr;
grid-template-columns: 1fr auto;
grid-template-columns: 1fr auto;
grid-template-columns: 1fr;
grid-template-columns: 50% 50%;

but they don't meet the requirements of both scenarios. Is this possible with css grid?

1 Answer 1

2

It can't really be done with grid because two columns are created in all your scenarios. And with two columns, there's no CSS method to automatically make a column switch to span 2 when a sibling vanishes. That would require a script.

You may want to consider using implicit instead of explicit columns. That may lead to a solution. Take a look here:

Otherwise, consider flex instead of grid. A solution with flex is relatively simple because there are no "track walls" dividing up flex lines. This allows flex items to have access to the full row.

.grid {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 50px;
}

header {
  flex: 0 0 100%;  /* consume all space; force siblings to next line */
  background: #0098db;
}

.left-stuff {
  flex: 1;         /* consume all free space; share space with other flex: 1 siblings */
  background: #ffadad;
}

.right-stuff {
  flex: 1;
  background: #73d073;
}
<!-- example with header and two columns -->
<div class="grid">
  <header>
    <h1>I'm the header</h1>
  </header>
  <div class="left-stuff">I'm the left stuff</div>
  <div class="right-stuff">I'm the right stuff</div>
</div>

<!-- example with header and one column -->
<div class="grid">
  <header>
    <h1>I'm the header</h1>
  </header>
  <div class="right-stuff">I'm the right stuff</div>
</div>

1
  • Thanks. Figured it might not be possible. The example I gave is the minimal version of what I'm actually dealing with and was hoping to grid the whole layout without touching markup. Cheers!
    – Matt Coady
    Commented Sep 6, 2018 at 23:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.