I create widgets for sites which I don’t own.
After injecting html, I do the following to style the widget:
var style = document.createElement('style'),
stylesString = 'minified css with a prefix for each selector eg. .my-prefix p {... }',
rules = document.createTextNode(stylesString);
style.type = 'text/css';
if(style.styleSheet) {
style.styleSheet.cssText = rules.nodeValue;
} else {
style.appendChild(rules);
}
document.getElementsByTagName('head')[0].appendChild(style);
But on some sites my styles are overridden.
Is there a way to apply the styles more precisely?
I don’t want (can’t) to use:
- iFrame
- !important on every property
This is most likely caused by the elements in question either having inline styles on them (for which you will have to use
!importantto override, if you want to use your current method of adding styles), or having styles with a higher selector precedence.My suggestion would be to make your selectors more specific by adding at least an
idto them – although this is still no guarantee your selectors will still be the most specific. It is entirely down to the quality of the stylesheet on the original site.