Setting RGBa backgrounds using inline CSS
I’m working on some code that is injected into a page using JavaScript and has to exist in an unknown environment. To make sure that the styling is not over-ruled by other CSS applied to the page I am adding some CSS as inline styles. This works fine until you try to apply an RGBa background with a hexadecimal fallback.
Usually you would declare something like this in your CSS.
div {
background-color: #666;
background-color: rgba(0,0,0,0.6);
}
All browsers apply the first background colour value, and this is then overridden by the second value in browsers that understand RGBa. Browsers that don’t understand RGBa just ignore it and continue to use the first value.
If you apply this inline however, it doesn’t work in IE7 or IE8.
<div style="background-color: #666;background-color: rgba(0,0,0,0.6);">content</div>
Inspecting the elements shows that the background colour value is empty.
As I am adding all of this code to the page using JavaScript I decided to try setting the styles using JavaScript at the same time.
div = document.createElement('div');
div.style.backgroundColor = "rgba(0,0,0,0.6)";
if (div.style.backgroundColor.indexOf("rgba") == -1) {
div.style.backgroundColor = "#666";
}
The trouble with this version is that IE7 and IE8 throw a JavaScript error when you try to set a RGBa value for the backgroundColor property. This gave me an idea I could use though. If setting an RGBa colour throws an error, then we can catch it, ignore it and set the value as the hexadecimal fallback.
div = document.createElement('div');
try {
div.style.backgroundColor = "rgba(0,0,0,0.6)";
}
catch(e) {
div.style.backgroundColor = "#666";
}
This is the method I am currently using. If you know of a better way, let me know in the comments.
comment
Please Leave a Reply
TrackBack URL :
Couldn’t you use modernizr to detect support for rgba?