Equally distribute list items in height (jQuery/CSS)

184 views Asked by At

I have a responsive website with a grid of divs.

When I open the page or resize the browser's width, these divs will automatically resize to adapt to the browser's width. As their width is changing, their height is changing too in order to keep their aspect ratio.

the first div embeds an unordered list made of several list items (which are displayed vertically in an "inline-block" style).

As told before, according to the width of the browser (when the page is refreshed or resized), the first div will automatically resize its height. What I would like to know is how I can automatically and equally change the height (or line-height, or padding or margin) of these list items in order for the list to always fill vertically the whole div.

It is important to know that the number of list items will vary from a page to another. It is given as a variable on page opening but the script should be able to work, whatever the number of items.

This is what I did with jQuery (with a php variable).

var dW=$(".mydiv").width();
var dH=$(".mydiv").height();
var liNum= <?php echo $how_many_li; ?>; 
var verticalSpace=  (dH / liNum) * 100;
verticalSpace= Math.round(verticalSpace) / 100;
$('.myListblock li a').css('line-height',verticalSpace+'px');
$('.myListblock').css('width',dW);
$('.myListblock').css('height',dH);

It kinda works but it is messy as sometimes it looks ok but sometimes it doesn't. 70% of the time it's ok and looks good but there are moments where the list goes out of the div's limit and moments where the list only occupies the 2/3 of it.

So, I would like to know if there is a more predictable/efficient/simple way to achieve what I want (pure CSS would be perfect but I don't know if it is possible).

Thank you.

1

There are 1 answers

2
Frogmouth On BEST ANSWER

I think you can do this with CSS only. I'm not 100% sure about Cross-browser compatible but it works in Chrome (right now I try to test with other browser).

HTML

<div class="main-wrapper">
    <ul class="myListblock">
        <li class="mydiv"><a href="#">div a</a></li>
        <li class="mydiv"><a href="#">div b</a></li>
        <li class="mydiv"><a href="#">div c</a></li>
        <li class="mydiv"><a href="#">div d</a></li>
        <li class="mydiv"><a href="#">div e</a></li>
    </ul>
</div>

CSS

.myListblock{
    display:table;
    width:100%;
    height:100%;
    margin:0;
    padding:0;
}

.myListblock li{
    display:table-row;
}

.myListblock li a{
    display:table-cell;
    vertical-align:middle;
}

But, .myListblock must has defined height.

Working example: http://jsfiddle.net/Frogmouth/czLgs9pu/