Prevent content from expanding grid items

后端 未结 3 1564
长发绾君心
长发绾君心 2020-11-21 06:32

TL;DR: Is there anything like table-layout: fixed for CSS grids?


I tried to create a year-view calendar with a big 4x3 grid for t

3条回答
  •  醉梦人生
    2020-11-21 07:03

    By default, a grid item cannot be smaller than the size of its content.

    Grid items have an initial size of min-width: auto and min-height: auto.

    You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

    From the spec:

    6.6. Automatic Minimum Size of Grid Items

    To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

    Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

    • Why don't flex items shrink past content size?

    This post also covers potential problems with nested containers and known rendering differences among major browsers.


    To fix your layout, make these adjustments to your code:

    .month-grid {
      display: grid;
      grid-template: repeat(6, 1fr) / repeat(7, 1fr);
      background: #fff;
      grid-gap: 2px;
      min-height: 0;  /* NEW */
      min-width: 0;   /* NEW; needed for Firefox */
    }
    
    .day-item {
      padding: 10px;
      background: #DFE7E7;
      overflow: hidden;  /* NEW */
      min-width: 0;      /* NEW; needed for Firefox */
    }
    

    revised codepen


    1fr vs minmax(0, 1fr)

    The solution above operates at the grid item level. For a container level solution, see this post:

    • How come minmax(0, 1fr) works for long elements while 1fr doesn't?

提交回复
热议问题