Here's the answer for people who hate browser inconsistency.
As explained, you need to test if this element has a transparent background, then if it does, walk through the DOM until you find a parent with background-color
set - but that means testing whatever string each browser chooses to return.
Firefox, IE and others return transparent
, Chrome/safari/webkit browsers etc return rgba(0, 0, 0, 0)
... and I personally don't trust that there won't be some other exception out there somewhere, now or in the future.
If you don't like the idea of trusting a string given to you by a browser (and you shouldn't), you don't have to: just test against the background-color
of an empty element.
Here's a JSBIN example of it in action. (to test on old IE, remove 'edit' from URL)
Usage: Plonk this code somewhere (it works as a jQuery plugin)...
(function($) {
// Get this browser's take on no fill
// Must be appended else Chrome etc return 'initial'
var $temp = $('<div style="background:none;display:none;"/>').appendTo('body');
var transparent = $temp.css('backgroundColor');
$temp.remove();
jQuery.fn.bkgcolor = function( fallback ) {
function test( $elem ) {
if ( $elem.css('backgroundColor') == transparent ) {
return !$elem.is('body') ? test( $elem.parent() ) : fallback || transparent ;
} else {
return $elem.css('backgroundColor');
}
}
return test( $(this) );
};
})(jQuery);
...then you can get the 'inherited' background colour of any element like this:
var backgroundColor = $('#someelement').bkgcolor();
Or if you want a fallback to be applied instead of 'transparent' if no background-color
is set here or anywhere behind this element (e.g. for matching overlays), send as an argument:
var backgroundColor = $('#someelement').bkgcolor('#ffffff');