Is it possible to add 1fr padding to a grid element in CSS?

Viewed 443

I'm trying to build this layout using a CSS grid.

enter image description here

The actual grid and its elements work fine using this simple markup and CSS:

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  column-gap: 40px;
  color: white;
}

.grid__col { }

.grid__col.grid__col--a {
  grid-column: 1/span 6;
  background: navy;
}

.grid__col.grid__col--b {
  grid-column: 7/span 4;
  background: grey;
}
<div class="grid">
  <div class="grid__col grid__col--a">A</div>
  <div class="grid__col grid__col--b">B</div>
</div>

But there's one issue. As you can see in the screenshot, the content inside the blue element should have a padding that's excatly 1fr (or even 2fr with column gap etc).

I know that there's subgrid coming, but only Firefox 71 supports it at the moment. I also tried to add another box with the background color that overlap with the actual content, like this:

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  column-gap: 40px;
  color: white;
}

.grid__col {
  grid-row: 1;
}

.grid__col.grid__col--c {
  grid-column: 1/span 6;
  background: navy;
}

.grid__col.grid__col--a {
  grid-column: 2/span 4;
}

.grid__col.grid__col--b {
  grid-column: 7/span 4;
  background: grey;
}
  <div class="grid">
    <div class="grid__col grid__col--c"></div>
    <div class="grid__col grid__col--a">A</div>
    <div class="grid__col grid__col--b">B</div>
  </div>
  

The problem is, that this box is always as high as the grid row and not like the actual content. This might be a problem, when the right container is higher than the left one.

Is there a way to accomplish this using CSS grid?

1 Answers

Use calc() and you can get the exact value of 1fr

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  column-gap: 40px;
  color: white;
}

.grid__col { }

.grid__col.grid__col--a {
  grid-column: span 6;
  padding:0 calc((100% - 5*40px)/6);   /* 100% = 6fr + 5 gaps ==> 1fr = (100% - 5 gaps)/6 */
  background: navy;
}

.grid__col.grid__col--b {
  grid-column: span 4;
  background: grey;
}
<div class="grid">
  <div class="grid__col grid__col--a">A</div>
  <div class="grid__col grid__col--b">B</div>
</div>

Related