Gildraths
Gildraths

Reputation: 376

How to limit a list by the a maximum div height?

We have a div that is fixed through:

.example_class{
    height:340px;
    width:340px;
}

Now we should display a list in that div. The list is generated according to a MySQL-Query. It should display as many elements as possible that are whole.

My issue now is that because of the fixed size there will be a line-break when the text is too long. This is intended behaviour but prevents me from just displaying x-elements. Cutting the text off after a certain length is also not allowed.

Do I have to count the number of letters for each MySQL-string that I got? Or what other options do I have?

EDIT Here how the list-entries are generated:

<div class="example_class">
    <h3>Jobs</h3>
    <ul>
        <?php for ($i = 1; $i <= count($getTopTenJobs); $i++) { ?>

            <li> <?php echo $getTopTenJobs[$i]['fld_title']; ?> </li>

        <?php } ?>
    </ul>
</div>

Upvotes: 2

Views: 567

Answers (2)

trincot
trincot

Reputation: 350270

PHP cannot know where the overflow will happen, since it depends on the font, different character widths, and even the zoom-level of the browser. And still when all these factors are the same, the overflow status might still be different across browsers.

So you need some post-processing in JavaScript, which will detect the overflow and then clip the contents until there is no more overflow.

To do that, add this script just before the ending </body> tag:

<script>

(function clip() {
    var divs = document.querySelectorAll('.example_class');
    for (var i = 0; i < divs.length; i++) {
        var div = divs[i];
        var ul = div.querySelector('ul');
        while (div.scrollHeight > div.clientHeight && ul.children.length) {
            var li = ul.children[ul.children.length-1];
            ul.removeChild(li);
        };
    }
})();

</script>

This will visit all those div tags on the page and check for each if there is an overflow. If so, repeatedly the last li is removed until there is no more overflow (or there are no more children).

Upvotes: 1

Shrikant Mavlankar
Shrikant Mavlankar

Reputation: 1153

Try something like this, It will calculate your div height and also each li height and keep only those li which are fit in the div.

I've deducted 50 from the div height for margin purpose. Let me know it is helpful for you.

<script>
$(document).ready(function () {

    var sum = 0

    $('.example_class ul li').each(function () {

        sum += $(this).height();

        if (sum > Number($(".example_class").height()) - 50) {

            $(this).remove();
        }
    });
});
</script>

Upvotes: 1

Related Questions