Horizontal scroll of grid with items width equal to its content

How do I make a container with horizontal scroll of its items with an item’s width equal to its content(like max-content) using css grid.

I tried this

display: grid;
grid-template-columns: repeat('dynamic value eq to no. of items', max-content);
height: 100%;
gap: 10px;

This does not work and I want to avoid using max-content because I read there is not much browser support.

1 thought on “Horizontal scroll of grid with items width equal to its content”

  1. You could use grid-auto-flow and grid-auto-columns to achieve the horizontal scroll. Then utilize minmax() to specify each grid items size. With a minimum value of 8rem (or another value of your choosing) and a maximum value of auto to replace max-content since there isn’t full browser support for that sizing keyword.

    Using auto as the maximum value is identical to using max-content. As a minimum it represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. minmax() – MDN

    .grid {
      display: grid;
      height: 100%;
      gap: 10px;
      grid-auto-columns: minmax(8rem, auto);
      grid-auto-flow: column;
      overflow-x: scroll;
    .blue {
      background: lightblue;
      height: 8rem;
      /* height: auto; use auto to allow the content to determine grid items height */
    <section class="grid">
      <div class="blue">1</div>
      <div class="blue">2</div>
      <div class="blue">3</div>
      <div class="blue">4</div>
      <div class="blue">5</div>
      <div class="blue">6</div>
      <div class="blue">7</div>
      <div class="blue">8</div>

Leave a Comment