I am currently working on a script that will be utilized across multiple pages and I am facing the challenge of ensuring that the elements it generates are not affected by the styling from the page's CSS.
It is not a common practice to do this in CSS, as typically the styles from the page take precedence. Therefore, the solutions for this issue might not be very straightforward. One approach could be to use a specific class and define rules for each element with that class, creating a tag-specific reset class like so:
a.untouched
div.untouched
.someOther.untouched
...etc
The effectiveness of this method may vary depending on how well-structured your original CSS is – a cleaner structure would require fewer instances of the untouched
elements.
In cases where the original CSS rules have higher specificity, even using the class method above may not suffice. In such situations, you may need to resort to using the !important
rule for all the reset rules, despite being considered bad practice:
a.untouched {color: black !important; font-size: 16px !important}
Although this solution may not be elegant, it could be the most practical way to address your issue.
A helpful tool for calculating selector specificity can be found here:
Below is a simple example featuring various paragraph variations:
p {color: #999; font-size: 14px; margin: 0 0 2px;}
p.red {color: red}
p.big {font-size: 20px}
p#superRed {color: red; text-shadow: 0 0 4px red;}
p > span {color: blue}
p.untouched, p.untouched > span {color: green !important; font-size: 12px !important; text-shadow: none !important;}
Originals:
<p>Test</p>
<p class="red">Test</p>
<p class="big">Test</p>
<p class="big red">Test</p>
<p id="superRed">Test</p>
<p><span>Test</span></p>
Untouched:
<p class="untouched">Test</p>
<p class="untouched red">Test</p>
<p class="untouched big">Test</p>
<p class="untouched big red">Test</p>
<p class="untouched" id="superRed">Test</p>
<p class="untouched"><span>Test</span></p>
JS version of the example above:
var els = document.querySelectorAll('#m *');
var style = {
'color': 'green',
'font-size': '12px',
'text-shadow': 'none'
}
for (var i = 0; i < els.length; i++) {
console.log(els[i], els[i].style['color']);
for(var s in style) {
els[i].style[s] = style[s];
}
}
p {color: #999; font-size: 14px; margin: 0 0 2px;}
p.red {color: red}
p.big {font-size: 20px}
p#superRed {color: red; text-shadow: 0 0 4px red;}
p > span {color: blue}
Originals:
<p>Test</p>
<p class="red">Test</p>
<p class="big">Test</p>
<p class="big red">Test</p>
<p id="superRed">Test</p>
<p><span>Test</span>
</p>
New ones:
<div id="m">
<p>Test</p>
<p class="red">Test</p>
<p class="big">Test</p>
<p class="big red">Test</p>
<p id="superRed">Test</p>
<p><span>Test</span></p>
<div>