CSS 多列列表,水平滚动,自动列宽和列高

CSS list with multiple columns with horizontal scrolling and automatic column width and height

我有一个自动生成的列表(项目的数量和它们的宽度事先不知道):

<div>Page header</div>
<div>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    ...
    <li>Ninety nine</li>
    <li>One hundred</li>
  </ul>
</div>
<div>Page footer</div>

我想要以下布局:

+-----------------------------------------+
| Page header                             |
|                                         |
| +-------------------------------------+ |
| |One    Five   Nine    Thirteen  .... | |
| |Two    Six    Ten     Fourteen  .... | |
| |Three  Seven  Eleven  Fifteen   Ninet| |
| |Four   Eight  Twelve  Sixteen   One h| |
| <[=======scrollbar=========]----------> |
|                                         |
| Page footer                             |
+-----------------------------------------+ <-- window (viewport) frame

所以

我知道如何针对固定的列数进行类似的设计,但不会针对自动调整屏幕区域的列数进行设计。

如果解决方案不简单,也许有现成的 .css 或 .js 可以执行此操作?

要让列表自动扩展以适合 window 的宽度,您可以使用以下 CSS,知道您可能需要扩展其他父元素并设置 margin: 0padding: 0

width: 100%;

要使列表在屏幕太大时滚动,请尝试使用以下 CSS 样式

overflow-x: scroll

或者如果列表太大时需要双向滚动,请使用此

overflow: scroll

您要求列表填充 window 宽度,但您说它应该使用水平滚动条水平滚动。这些是相互排斥的。如果它适合 window 宽度,则不应有水平滚动条。无论如何,水平滚动条的设计很糟糕,尽管垂直滚动条还可以。

您可以做的是填充一个 HTML table,然后循环检查宽度的行和单元格以查看您拥有的内容。之后,您可以使用不同的每行单元格数或每列宽度重新填充 table。也许你可以这样做两到三次,但这对我来说似乎很笨拙。没有执行此操作的自动功能。我的建议是使用最适合的单元格宽度作为常量,这是通过反复试验得出的,并在发生溢出时使用 CSS 属性丢弃溢出内容。

我想这就是您要找的一切。它主要是用 JQuery 完成的以达到效果(其中一些在 CSS 中)。它也是动态的,因此它应该处理您拥有的任何数量的 li。我在下面的代码中解释了它是如何工作的:

//find the number of li's
var numberOfResults = $('li').length;

//set how many li's you want per row
var numberPerRow = 4;

//pull the first ul for later use
var $firstUL = $('ul');

//divide the number of li's from the number you want per row then round the number
var numberOfRows = Math.ceil(numberOfResults/numberPerRow);

//find the width of the largest li for later use
var maxWidth = Math.max.apply( null, $( 'li' ).map( function () {
  return $( this ).outerWidth( true );
}).get() );

//set container width the width of all rows * the width of each one
$(".container").css({"width": (maxWidth*numberOfRows)+"px"})

//add a ul depending on the number of rows
for(var i=1;i<=numberOfRows;i++){
   $(".container").append('<ul></ul>');
}

// go through each row and add the lis
for(var i=1;i<=numberOfRows;i++){
   $firstUL.find('li:lt('+(numberPerRow)+')').appendTo('ul:eq('+(i)+')');      
}

//loop through all of the lis and set the width to the max
$("li").each(function(){
   $(this).css({"width":maxWidth+"px"})
});

FIDDLE