JSFiddle - React, Tailwind, and code Playground
HTML
<p>
Blue = fixed. Green = auto;
</p>
<div>
This div has auto height.
</div>
<div class="auto" style="height:40px;">
This div has fixed height.
</div>
<div class="auto" style="height:auto;">
This div has auto height.
</div>
<div id="fix" class="auto">
This div has fixed height (testing css specificity).
</div>
<div class="auto">
This div has auto height.
</div>
<div class="fix">
This div has fixed height.
</div>
<div class="importantauto" style="height:10px;">
BUG: This div is auto-height. Though it has fixed height set using "style", a css rule overrides it with the "!important" directive. It is the same if it was set using an "#id" css rule. Did I even mention how much I hate the stupid CSS specificity priority
system? Anyway, when using the MatchedCSSRules API we get the wrong value as well.
</div>
<p>Thank you.</p>
CSS
div {
margin: 10px;
}
.auto {
height: auto;
}
#fix,.fix {
height: 50px;
}
.importantauto {
height: auto !important;
}
.mark_auto {
outline: 2px solid green;
}
.mark_fixed {
outline: 2px solid blue;
}
JavaScript
// receive a jQuery element
// return true for elements with auto height (90-100% is considered auto as well)
// return false for elements with fixed height
function is_height_auto($e) {
var e = $e[0],
// check fixed style:
chk = function(value) {
return /\d/.test(value) && !/^(100|9\d)\%/.test(value);
};
// start from the first, easiest, inline styles
if (chk(e.style.height)) {
console.log('fixed for having style', e.style.height)
return false;
}
// start from the first, easiest, inline styles
var overflow = getComputedStyle(e)['overflow'];
if (overflow == 'scroll' || overflow == 'auto' || (e.tagName == 'BODY' && overflow == 'visible')) {
console.log('auto for having overflow or is body', getComputedStyle(e)['overflow'], e.tagName);
return true;
}
// deprecated chrome way - check each rule that applies to the element
if (typeof getMatchedCSSRules == 'function') {
var i, MatchedCSSRules = getMatchedCSSRules(e) || [];
for (i = MatchedCSSRules.length; i; i--) {
if (MatchedCSSRules[i - 1].style.height) {
console.log('found height at MatchedCSSRules[' + (i - 1) + ']: ', MatchedCSSRules[i - 1], ' All matches: ', MatchedCSSRules)
return !chk(MatchedCSSRules[i - 1].style.height);
}
}
}
// append something, see if height was changed, remove the something
var originalHeight = $e.height(),
$ghost = jQuery('<b style="display:block;height:1px;width:1px;padding:0;margin:0;">').appendTo($e),
newHeight = $e.height();
$ghost.remove(); // cleanup
console.log('Using a ghost got ',newHeight > originalHeight,' originalHeight=' + originalHeight + ' newHeight=' + newHeight)
return newHeight > originalHeight;
} //is_height_auto()
$('div').each(function() {
var $e = $(this);
if (is_height_auto($e)) {
$e.addClass('mark_auto');
} else {
$e.addClass('mark_fixed');
}
});