3

I'm working with CSS Grid and I noticed a behavior I don't fully understand.

body {
  background: rgb(58, 58, 59);
}

.grid-parent {
  height: 90vh;
  display: grid;
  gap: 5px;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: 1fr 2fr 4fr;
}

.grid-parent>* {
  background-color: rgb(102, 102, 102);
}

.clildren-a {
  grid-row: 1 / 4;
  grid-column: 1 / 2;
}

.clildren-b {
  grid-row: 1 / 2;
  grid-column: 2 / 4;
}

.clildren-c {
  grid-row: 1 / 4;
  grid-column: 4 / 5;
}

.clildren-d {
  grid-row: 2 / 4;
  grid-column: 2 / 3;
}

.clildren-e {
  grid-row: 2 / 4;
  grid-column: 3 / 4;
}

.clildren-f {
  grid-row: 1 / 4;
  width: 90px;
}
<body>
  <div class="grid-parent">
    <div class="clildren-a">A</div>
    <div class="clildren-b">B</div>
    <div class="clildren-c">C</div>
    <div class="clildren-d">D</div>
    <div class="clildren-e">E</div>

    <div class="clildren-f">f</div>
  </div>
</body>

Even though I defined grid-template-columns: repeat(4, 1fr); (4 columns), I notice that the browser creates 6 column grid lines instead of 5, seemingly to accommodate .children-f.

Why is an extra column line created?

How should I properly place .children-f without creating extra implicit columns?

8
  • I only see 5 columns, how do you see 6? Commented Sep 15 at 10:36
  • Where do you want -f to go? Commented Sep 15 at 10:53
  • 1
    @a-haworth It should follow the natural behaviour and place the item at the end of the row, not create a new column. Commented Sep 15 at 11:02
  • 1
    you told f to go to first row by using grid-row: 1/4 so it does Commented Sep 15 at 11:11
  • 1
    Perhaps reword your original question with what you actually need to know so someone else can help. Commented Sep 15 at 15:07

1 Answer 1

2

The extra column appears because .clildren-f doesn’t have an explicit grid-column assigned. In CSS Grid, if an item is placed without specifying a column, the browser will try to place it in the next available grid cell. If all defined columns are occupied, it creates an implicit column to fit the item. That’s why your 4-column grid ends up showing a 5th column line.

Explicitly assign .clildren-f to an existing column, for example:

.clildren-f {
  grid-row: 1 / 4;
  grid-column: 4 / 5;
  width: 90px;
}

Or, if you want it to span multiple columns, make sure it stays within the repeat(4, 1fr) columns using proper grid-column start/end values.

Without a grid-column, the browser always creates an implicit column to accommodate the item.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.