How to make the column sizes of the CSS grid strict / consistent

I have two layout components on one page. The underlying grid is 12 columns. The first component has two parts, side by side, spanning 9 columns and 3 columns. The second component has four parts, side by side, each spanning 3 columns.

The code is as follows:

.container {
  width: 100%;
  max-width: 1140px;
  margin: 0 auto;
}
.stack > * + * {
  margin-top: 1rem;
}
.grid__cell {
  outline: 1px solid black;
}
.grid {
  display: grid;
  gap: 1rem;
}
.grid--a {
  grid-template-columns: 9fr 3fr;
}
.grid--b {
  grid-template-columns: 3fr 3fr 3fr 3fr;
}
<div class="container stack">
  <div class="grid grid--a">
    <div class="grid__cell"><p>This column should take up 3/4 of the width</p></div>
    <div class="grid__cell"><p>This column should take up 1/4 of the width</p></div>
  </div>
  <div class="grid grid--b">
    <div class="grid__cell"><p>This column should take up 1/4 of the width</p></div>
    <div class="grid__cell"><p>This column should take up 1/4 of the width</p></div>
    <div class="grid__cell"><p>This column should take up 1/4 of the width</p></div>
    <div class="grid__cell"><p>This column should take up 1/4 of the width</p></div>
  </div>
</div>

I would expect the end portion of each component to have the same width, but they are slightly different. (In my real-world example, the difference is much greater). I was wondering how to make it so that the grid size is strict and not affected by the content as I have to make sure all components are in line.

Thanks.

Leave a Comment