One UL list split into multi columns with fixed he

2019-05-11 20:24发布

问题:

I would like to create one UL list that will contain a variable number of LI elements. I would like the heigh of the container to be max 500px. Which means if i have more li elements that go over that 500px height i want it to turn into 2 columns. If there is more then can fit for 2 columns i would like it to turn into 3 columns. I have enough space to fix max 5 columns and the data will never go over that amount.

Any idea how i can do this? Any jquery, css tricks? or do i need to handle each scenario server side to do this.

Example 1

    list entry    list entry 
    list entry    list entry
    list entry    list entry
    list entry    list entry
    list entry    


 Example 2
    list entry    list entry     list entry
    list entry    list entry     list entry
    list entry    list entry     list entry
    list entry    list entry
    list entry    list entry


 Example 3
    list entry    list entry     list entry     list entry
    list entry    list entry     list entry     list entry
    list entry    list entry     list entry     list entry
    list entry    list entry     list entry
    list entry    list entry     list entry

If it cant be achieved without one UL then i am open to that.

Thanks!

回答1:

http://jsfiddle.net/eaewX/1/

If you encapsulate each list in a <div>, setting columns, column-width, or column-count on <div>, it will break the list into columns appropriately.

edit: It is in the jsfiddle, but I should clarify you'll need to use browser extensions for these properties currently, i.e. -webkit-, -moz-, -o-

For reference:

https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_multi-column_layouts

http://dev.w3.org/csswg/css3-multicol/#columns



回答2:

Here's a working solution

/* set max height of containers */
var maxHt=500;/* may need to adjust based on css*/

var $list=$('#startList')
var $container=$list.parent();

var $li=$list.find('li');

var totHt=0;    
var totItems=$li.length;
$li.each(function( idx){

    var ht=$(this).height();
    if( totHt + ht >= maxHt || idx==totItems-1){
        $('<ul>').append( $(this).prevAll().andSelf() ).appendTo( $container );
        totHt=0;
    }else{
        totHt += ht;
    }  

});

$list.remove()

DEMO: http://jsfiddle.net/rzw64/3/

Note that height set on UL needs a little extra than max height used for calcs. Additional CSS will help or can add code to get dynamic height of parent container to set maxHt allowed