3

I have a HTML template:

 <ul>
           <li>1
    <li>1
    <li>22
    <li>1
    <li>1
    <li>333
    <li>1
    <li>1
    <li>22
    <li>1
    <li>1
</ul>

ul container width is determined.

I want to build table style grid layout with undefined number of columns.

Min column size is restricted by content size of li.

Max column size could be whole width of the container ul.

Here is example I want to achive. enter image description here

Is it possible using CSS Grid layout or any other layout?

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
JayFry
  • 97
  • 1
  • 2
  • 10
  • Essentially....NO. You don't really have columns here, you have one long wrapping row...so you can't set the column(s) width because there aren't any. If you define the *number* of columns then something could be worked out in CSS-Grid I suspect. – Paulie_D Mar 23 '18 at 11:14
  • I thought maybe it could be done with some magic and: `grid-template-columns: repeat(auto-fill, minmax(???, ???))` I have tried a lot of things and it didn`t work out. – JayFry Mar 23 '18 at 11:42
  • the `table` element does a great job at this – oldboy Mar 24 '19 at 21:56

1 Answers1

3

For an undefined number of columns, I don't believe it is possible with CSS Grid.

With regard to your comment:

I thought maybe it could be done with some magic and: grid-template-columns: repeat(auto-fill, minmax(???, ???))

That is the logical way to go, but it's a dead end.

The necessary rule would be something along these lines (using auto-fill or auto-fit):

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

There are other possible variations using min-content and fit-content().

Alas, these cannot work because the repeat() function, when used with automatic repetitions, must contain at least one fixed length.

7.2.2.1. Syntax of repeat()

Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.

  • An intrinsic sizing function is min-content, max-content, auto, fit-content().

  • A flexible sizing function is <flex> (fr).

The closest you can get with CSS Grid would be with grid-template-columns: auto, an inline-level grid, and a defined number of columns. I'll post this solution for general info.

ul {
  display: inline-grid;
  grid-template-columns: repeat(4, auto);
  grid-gap: 1px;
}

li {
  background-color: white;
}

ul {
  background-color: black;
  border: 1px solid black;
  list-style: none;
  padding: 0;
  font-size: 1.5rem;
}
<ul>
  <li>1</li>
  <li>1</li>
  <li>22</li>
  <li>1</li>
  <li>1</li>
  <li>333</li>
  <li>1</li>
  <li>1</li>
  <li>4444</li>
  <li>1</li>
  <li>1</li>
  <li>1</li><!-- added for demo -->
</ul>

Here's a separate issue that may arise when building a table with Grid Layout:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701