CSS 固定最大高度时自动列数

CSS auto column-count when max-height is fixed

我希望实现一个布局,其中元素(在我的例子中是 <ul>)在高度达到特定限制时扩展到 2(或更多)列。

因此,例如,如果高度只够 3 个项目,而我有 5 个,则第 4 和第 5 个项目转到第二列,仅在需要时才创建。

我尝试通过将 max-height 设置为 herecolumn-count 并通过 [=18= 将 column-width 设置为 auto 来做到这一点] (我也试过分别设置它们,同样的行为)。

另一方面,如果我将 column-count 更改为固定整数,它可以工作并平衡项目,但这不是我需要的动态。 (如果我只有 2 个元素,我不想为它们创建 2 列)。

有没有办法固定高度,当高度不足以容纳所有项目时自动添加列?

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>

首先,要使 CSS 列 有效,您必须设置 column-widthcolumn-count。 CSS 如果您不设置任何列, 列将不起作用

如果我理解正确,您需要使用 column-fill property. Unfortunately, only Firefox supports it now. Check out this code snippet仅限 Firefox)。

ul#list {
    font-family: sans-serif;
    list-style: none;
    background: #dddddd;
    max-height: 200px;

    /* Works only in Firefox! */
    -moz-columns: 100px auto;
    -moz-column-gap: 10px;
    -moz-column-rule: 1px solid rgba(100, 30, 30, 0.4);
    -moz-column-fill: auto;
}

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>

我想,你可以使用 flex in your case. See example:

ul#list {
    font-family: sans-serif;
    list-style: none;
    background: #dddddd;
    height: 200px;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-flow: column wrap;
    flex-flow: column wrap;
}

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>