Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css grid variable column width and wrapping

Tags:

css

css-grid

I have what I thought was a simple task : given x items, show them in a grid, with each column being the width of the content. If the number of columns exceeds the width of the container, create a new row and continue

I have managed to get the columns to display and wrap, but only if I define a fixed-width for the column

https://stackblitz.com/edit/angular4-dxkvmt

how can I make each "label" on each row fit to the content but move to a new row when the number of labels would exceed the available view space ?

I have tried

grid-template-columns: repeat(auto-fill,max-content);

this gives one row per label

grid-template-columns: repeat(auto-fill,minmax(20px,max-content));

makes all columns 20px .. but they do flow properly on resize

would appreciate some pointers. I am not particularly skilled at css grid so may have overlooked something easy

like image 702
jmls Avatar asked Jul 09 '26 12:07

jmls


1 Answers

I thought about doing the same, start with a grid of 12 frames and go down to something like 8fr and end with 4fr. E.g.

grid-template-columns: repeat(4, 1fr);

Then, using a media query I realised that besides of making smaller the grid I should also make bigger the size of the layers, where the limit of the number of frames to span would the size of the grid. For instance, lets image this basic grid:

.layout.grid {
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    grid-gap: 16px 24px;
    gap: 16px 24px;

   .frame, .row {
    display: grid;
    place-items: center;
    grid-column: auto;
  }

  .span-1 {
    grid-column: auto / span 1;
  }

  .span-2 {
    grid-column: auto / span 2;
  }

  .span-3 {
    grid-column: auto / span 3;
  }

  .span-4 {
    grid-column: auto / span 4;
  }

  .span-5 {
    grid-column: auto / span 5;
  }

  .span-6 {
    grid-column: auto / span 6;
  }

  .span-7 {
    grid-column: auto / span 7;
  }

  .span-8 {
    grid-column: auto / span 8;
  }

  .span-9 {
    grid-column: auto / span 9;
  }

  .span-10 {
    grid-column: auto / span 10;
  }

  .span-11 {
    grid-column: auto / span 11;
  }

  .span-12, .row {
    grid-column: auto / span 12;
  }
}

It will look like this

grid 12

But in the media query, lets say screen and (max-width: 1278px) there is a code like

.layout.grid {
    grid-template-columns: repeat(4, 1fr) auto;

    [class^="span-"], .row {
      grid-column: auto / span 4;
    }

    .span-1 {
      grid-column: auto / span 1;
    }

    .span-2 {
      grid-column: auto / span 2;
    }

    .span-3 {
      grid-column: auto / span 2;
    }
}

The result looks like this grid4

The size of the frame is delimited to 1fr and you must be aware of the order of the frames as well. You can start from this point forward to build a more mature solution. But I think you get the idea.

like image 165
EliuX Avatar answered Jul 13 '26 15:07

EliuX