I wish to achieve a layout where an element (in my case a <ul>
) expands to 2 (or more) columns when the height reaches a certain limit.
So for example, if the height is only enough for 3 items, and I have 5, the 4th and 5th item go to the second column, which is only created if needed.
I tried to do this by setting the max-height
as suggested here with column-count
and column-width
set to auto
via the columns
(I tried setting them separately too, same behaviour).
If on the other hand I change the column-count
to a fixed integer, it works and balances the items, but this is not dynamic as I need it. (If I have only 2 elements I don't want to create 2 columns for them).
Is there a way to have the height fixed, and the columns automatically added when the height is not enough to fit all the items?
ul#list {
font-family: sans-serif;
list-style: none;
background: #dddddd;
max-height: 200px;
columns: auto auto;
-webkit-columns: auto auto;
-moz-columns: auto auto;
/** This works, but fixes the columns to 2, which is not what I want.
columns: 2 auto;
-webkit-columns: 2 auto;
-moz-columns: 2 auto;
*/
column-gap: 10px;
-webkit-column-gap: 10px;
-moz-column-gap: 10px;
column-rule: 1px solid black;
-webkit-column-rule: 1px solid rgba(100, 30, 30, 0.4);
-moz-column-rule: 1px solid rgba(100, 30, 30, 0.4);
}
li {
height: 20px;
padding: 2px;
}
<div id="outer">
<ul id="list">
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
<li>Item #4</li>
<li>Item #5</li>
<li>Item #6</li>
<li>Item #7</li>
<li>Item #8</li>
<li>Item #9</li>
<li>Item #10</li>
<li>Item #11</li>
<li>Item #12</li>
</ul>
</div>
First of all, to make CSS Columns work you have to set
column-width
orcolumn-count
. CSS Columns won't work if you doesn't set any of it.If I understand right, you need to use column-fill property. Unfortunately, only Firefox supports it now. Check out this code snippet (Firefox only).
I think, you could use flex in your case. See example: