Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining the number of rows in CSS grids

Tags:

html

css

css-grid

I have a slightly hypothetical question:

If I had a <ul>, and I wanted to use css grids to display the <li> in a vertical list, is there a way to automate this, so that if the number of <li> changed, the number of rows would increase/decrease automatically?

Example:

ul {
  display: grid;
  grid-template-rows: repeat(NUM, 1fr);
}

<ul>
  <li>item one</li>
  <li>item two</li>
  <li>item three</li>
</ul>

Here the NUM specifies the number of rows in the template, but if I were to add another <li> I would then have to go and change the NUM value.

Is there a way to recognise the number of child elements and set the number of rows automatically accordingly?

I am asking hypothetically in case I have missed any cdd grid specs, - I am not looking for any hacks around, and especially am not looking for a javascript workaround - it just seems a little too inflexible not to have the option to automate this, I am new to grids and am just figuring out how it works.

like image 873
Jonny Avatar asked Nov 07 '22 10:11

Jonny


1 Answers

Simply define grid-auto-rows and you don't need to know the number of items

ul {
  display: grid;
  grid-auto-rows:1fr;
  margin:10px;
  padding:0;
}
ul li {
  border:1px solid;
  list-style-type:none;
}
<ul>
  <li>item <br>one</li>
  <li>item two</li>
  <li>item three</li>
</ul>

<ul>
  <li>item <br>one</li>
  <li>item two</li>
  <li>item three</li>
  <li>item two</li>
  <li>item three</li>
</ul>

<ul>
  <li>item <br>one</li>
  <li>item two</li>
</ul>

If a grid item is positioned into a row or column that is not explicitly sized by grid-template-rows or grid-template-columns, implicit grid tracks are created to hold it. This can happen either by explicitly positioning into a row or column that is out of range, or by the auto-placement algorithm creating additional rows or columns. The grid-auto-columns and grid-auto-rows properties specify the size of such implicitly-created tracks. ref

like image 146
Temani Afif Avatar answered Nov 11 '22 03:11

Temani Afif