Posts Tagged: CSS

About table with `display: block` and `overflow-y: auto`

Few days ago my college and I had a page with an extra wide table on it which breaked the page body that is the horizontal scroll appeared on the whole page. We solved the problem with adding the following style on the table: { display: block; overflow-y: auto; max-width: 10px /* any low value here */ }.

But as you may know the tables are not supposed to wear display: block CSS declaration and that was why we failed trying to create something universal for all the tables.

We decided we have to check if the table is extra wide or not and found a quite simple solution, this small: jquery plugin from the answer:

$.fn.hasOverflow = function() { 
    var $this = $(this); 
    var $children = $this.find('*'); 
    var len = $children.length; 
 
    if (len) { 
        var maxWidth = 0; 
        var maxHeight = 0 
        $children.map(function() { 
            maxWidth = Math.max(maxWidth, $(this).outerWidth(true)); 
            maxHeight = Math.max(maxHeight, $(this).outerHeight(true)); 
        }); 
 
        return maxWidth > $this.width() || maxHeight > $this.height(); 
    } 
 
    return false; 
};

We edited it first to make it taking only width in account and then used it in the following way: $('body').hasOverflow().

But it did not work somethimes (probably something more has been changed on the page) and what is also bad thing is that it selects so huge amount of elements on a big pages that it really impacts the performance. But the next day we started to solve it again and in a few minutes we came with a very simple solution:

$(window).width() < $('body')[0].scrollWidth

It works fine by now! We needed just to sleep on it

Про table с `display: block` и `overflow-y: auto`

Недавно была у нас страничка, там появлалась очень широкая таблица, которая разрывала страницу, т.е. заставляла появиться горизонтальный скролл на body. Мы решили эту проблему добавлением стиля на таблицу, а именно { display: block; overflow-y: auto; max-width: 10px /* любая маленькая величина */ }.

Но как известно, таблицы не предназначены для того, чтобы на них вешался display: block, поэтому несмотря на многочисленные попытки сделать что-то универсальное, у других, более узких таблиц, возникли проблемы.

Мы решили, что надо определять, рвёт ли таблица страницу, или не рвёт.

Тут же нашли решение – вот такой компактный jquery-плагин здесь:

$.fn.hasOverflow = function() { 
    var $this = $(this); 
    var $children = $this.find('*'); 
    var len = $children.length; 
 
    if (len) { 
        var maxWidth = 0; 
        var maxHeight = 0 
        $children.map(function() { 
            maxWidth = Math.max(maxWidth, $(this).outerWidth(true)); 
            maxHeight = Math.max(maxHeight, $(this).outerHeight(true)); 
        }); 
 
        return maxWidth > $this.width() || maxHeight > $this.height(); 
    } 
 
    return false; 
};

Мы подправили его так, чтобы рассматривалась только ширина и использовали его следующим образом: $('body').hasOverflow().

Однако в некоторых случаях он не срабатывал (может быть ещё что-то другое изменилось на странице) и кроме этого не очень приятно, что выборка элементов может быть чересчур громоздкой – это может даже влиять на тормознутость страницы. Но на следующий день мы начали думать над этим заново и очень скоро пришли к очень простому методу проверки:

$(window).width() < $('body')[0].scrollWidth

Пока исправно работает! Утро вечера мудренее