Search code examples
csscss-gridword-wrap

Having a "display: inline-block" as a parent to a "display: grid" element without having text overlap?


I'm trying to arrange a set of statistics such that:

  • they are displayed on a single horizontal line
  • the enclosing element is no wider than it needs to be to contain the content
  • there should be a fixed gap between statistics

I tried implementing this using display: grid. Here is my approach:

.outer {
  background-color: yellow;
  display: inline-block;
}

.stats {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
}
<div class="outer">
  <div class="stats">
    <div class="stat">
      <strong>Value:</strong> 1,234,568
    </div>
    <div class="stat">
      <strong>Another value:</strong> 98,765
    </div>
    <div class="stat">
      <strong>Test value:</strong> 83,263
    </div>
  </div>
</div>

Unfortunately, this results in some strange overlapping. Despite there being plenty of room for the .outer element to expand, the statistics are wrapped over several lines and the text runs into other columns:

enter image description here

How can I avoid this problem? I tried adding:

.stat {
  white-space: nowrap;
}

...but the text still "runs" together. What am I missing?


Solution

  • The main problem stems from this declaration:

    grid-template-columns: repeat(auto-fit, minmax(0, 1fr))
    

    You're setting the columns to shrink to zero width.

    Also, 1fr does nothing here, because there is no free space in the container. (You have the primary container set to inline-block, i.e., min-width. This means no extra space.)

    At a minimum, these commands appear to be confusing the inline-block algorithm.

    Consider leaving the columns at auto width (a default setting).

    And, perhaps, setting them to appear in the first row. (I used the grid-auto-flow: column technique.)

    .outer {
      background-color: yellow;
      display: inline-block;
    }
    
    .stats {
      display: grid;
      grid-gap: 20px;
      grid-auto-flow: column;
    }
    <div class="outer">
      <div class="stats">
        <div class="stat">
          <strong>Value:</strong> 1,234,568
        </div>
        <div class="stat">
          <strong>Another value:</strong> 98,765
        </div>
        <div class="stat">
          <strong>Test value:</strong> 83,263
        </div>
      </div>
    </div>