im playing with css 3 grid and i have one question. I created demo:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
</ul>
ul
{
border: 3px solid goldenrod;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 50px;
margin: 0;
padding: 0;
grid-gap: 10px;
}
li
{
background: pink;
margin: 0;
padding: 0;
list-style: none;
text-align: center;
line-height: 50px;
}
link: http://jsbin.com/mosijijewe/edit?html,css,output
Expected result is
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
etc.
My question: is possible to get with some grid value or some trick example below? (without some manual definition, because I do not know how many lines will be in advance)
1 | 4 | 7
2 | 5 | 8
3 | 6 | 9
If you don't mind setting as many css rules as the maximum expected number of rows, this trick can work for you:
Use a content query to force some elements, based in the total number of elements, to go to a specific row
var numElements = 4;
function add () {
var ul = document.querySelector("ul");
var li = document.createElement("li");
li.appendChild(document.createTextNode(numElements));
ul.appendChild(li);
numElements++;
}
ul {
border: 3px solid goldenrod;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 50px;
margin: 0;
padding: 0;
grid-gap: 10px;
width: 300px;
grid-auto-flow: column;
}
li {
background: pink;
margin: 0;
padding: 0;
list-style: none;
text-align: center;
line-height: 50px;
}
li:nth-child(2):nth-last-child(n + 3) {
grid-row: 2;
background: tomato;
}
li:nth-child(3):nth-last-child(n + 5) {
grid-row: 3;
background: tomato;
}
li:nth-child(4):nth-last-child(n + 7) {
grid-row: 4;
background: tomato;
}
li:nth-child(5):nth-last-child(n + 9) {
grid-row: 5;
background: tomato;
}
li:nth-child(6):nth-last-child(n + 11) {
grid-row: 6;
background: tomato;
}
li:nth-child(7):nth-last-child(n + 13) {
grid-row: 7;
background: tomato;
}
li:nth-child(8):nth-last-child(n + 15) {
grid-row: 8;
background: tomato;
}
li:nth-child(4):nth-last-child(1) {
grid-row: 1;
background: bisque;
}
<button onclick="add()">Add item</button>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
References for quantity queries:
a list apart
css tricks
online tool
Another option might be to use column-count rather than grid:
ul
{
column-count: 3;
}
li
{
background: lightslategray;
list-style: none;
text-align: center;
line-height: 50px;
margin-bottom: 5px;
}
demo: https://codepen.io/RuaScribe/pen/PoYEaEw
info: https://css-tricks.com/almanac/properties/c/column-count/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With