I have this code:
.flex #left {
min-height: 230px;
}
#files {
display: flex;
flex-wrap: wrap;
list-style: none;
margin: 0;
padding: 10px;
position: relative;
user-select: none;
width: 100%;
}
#files li {
flex: 1;
max-width: 250px;
min-width: 200px;
width: 100%;
}
<div class="flex">
<div id="left">
<ul id="files">
<li>1</li>
<li>2</li>
<li>3</li>
...
</ul>
</div>
</div>
So, the <li>
are displayed from left to right, then from top to bottom, but I would like them to be displayed from top to bottom, then from left to right.
I don’t know in advance the number of li
.
I would like it to be on 4 columns maximum and that the <div id="left">
has a fixed height of, for example, 400px
, with a vertical scrollbar that appears if necessary according to the number of li
.
The width of <div id="left">
can change, for example if the user decreases the width of his browser window.
The number of columns should adapt accordingly, knowing that each column is max-width: 250px; min-width: 200px;
2
I would use a multi-column layout to implement this. Multiple columns give you the top-to-bottom then left-to-right arrangement you are looking for. These are the key declarations:
#files {
columns: 200px 4;
gap: 10px;
max-width: 1030px; /* 4 times 250px plus 3 times 10px */
}
The first declaration says that we want columns with a minimum width of 200 pixels, and that we want a maximum of four columns.
The second declaration says that we want the gap between the columns to be 10 pixels, which matches the padding of the #files
list.
The third declaration says that we want the total maximum width to be 1030 pixels, which is enough for four columns of 250 pixels each, plus three gaps of 10 pixels each. So while this limit is applied on the total width, it effectively limits our column width to a maximum of 250 pixels when there are four columns.
Note that my proposed solution does not limit the maximum width of our columns when there are fewer than four columns. If you really want to set a maximum width in this scenario, you could give #files li
a max-width
of 250px
. However, this causes the gaps between the columns to appear larger, and I don’t like the look of it. On the narrower viewports, I prefer the columns to stretch to fill the viewport.
.flex #left {
background: purple;
min-height: 230px;
max-height: 400px;
overflow: auto;
}
#files {
list-style: none;
margin: 0;
padding: 10px;
user-select: none;
columns: 200px 4;
gap: 10px;
max-width: 1030px; /* 4 times 250px plus 3 times 10px */
background: pink;
}
#files li {
background: yellow;
}
<div class="flex">
<div id="left">
<ul id="files">
<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>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
<li>21</li>
<li>22</li>
<li>23</li>
<li>24</li>
</ul>
</div>
</div>
After running this snippet, use the full page link to test the responsive behaviour.