htmlcsscss-grid

CSS grid taking width of all children instead of just columns


I have this CSS grid that flows vertically and wraps to a new column when the first is full. I expected the width of this grid element to be just the width of its columns. However, it seems to be taking the sum of the widths of all its children.

Specifically, if you change the width of one of the shorter elements (e.g. change 4a to 4aa), though the width of the column it is in does not change, the width of the entire grid does. This doesn't seem like correct behavior.

How can I ensure that the grid takes just the width of its columns?

.parent {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.grid {
  border: 1px solid black;
  height: 200px;
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: repeat(auto-fit, 35px);
  grid-auto-columns: min-content;
}

.grid > * {
  display: flex;
  border: 1px solid gray;
}
<div class="parent">
  <p>label</p>
  <div class="grid">
    <div>1aaaaa</div>
    <div>2aaa</div>
    <div>3aa</div>
    <div>4a</div>
    <div>5aa</div>
    <div>6aa</div>
    <div>7a</div>
  </div>
</div>

The following would be the expected behavior, but I would like the parent to be a column flexbox.

.grid {
  border: 1px solid black;
  height: 200px;
  display: grid;
  width: min-content;
  grid-auto-flow: column;
  grid-template-rows: repeat(auto-fit, 35px);
  grid-auto-columns: min-content;
}

.grid > * {
  display: flex;
  border: 1px solid gray;
}
<div class="parent">
  <p>label</p>
  <div class="grid">
    <div>1aaaaa</div>
    <div>2aaa</div>
    <div>3aa</div>
    <div>4a</div>
    <div>5aa</div>
    <div>6aa</div>
    <div>7a</div>
  </div>
</div>


Solution

  • Reason

    It's a Chromium bug.
    Chromium-based browsers calculate width before applying autopositioning.

    Your snippet works just fine in Firefox.

    Solution

    Set min-height and max-height instead of just height.

    .parent {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    
    .grid {
      border: 1px solid black;
      min-height: 200px;
      max-height: 200px;
      display: grid;
      grid-auto-flow: column;
      grid-template-rows: repeat(auto-fit, 35px);
      grid-auto-columns: min-content;
    }
    
    .grid > * {
      display: flex;
      border: 1px solid gray;
    }
    <div class="parent">
      <p>label</p>
      <div class="grid">
        <div>1aaaaa</div>
        <div>2aaa</div>
        <div>3aa</div>
        <div>4a</div>
        <div>5aa</div>
        <div>6aa</div>
        <div>7a</div>
      </div>
    </div>