Reputation: 6708
I'm making a simple greasemonkey script for school that adds an ugly yellow box with some links to all websites. Currently I simply do this:
var guesses_div = document.createElement("div");
guesses_div.style.position = "fixed";
guesses_div.style.right = "0";
guesses_div.style.bottom = "0";
guesses_div.style.backgroundColor = "rgb(255, 255, 0)"
// here I add some links to the "guesses_div"
This code works fine. However, it inherits the style from the web page it's on. Is there a way to prevent this? Other than overriding all the style elements one by one?
Thanks!
Upvotes: 1
Views: 1510
Reputation: 66365
Yes it's possible by creating Web Components which render their content in the Shadow DOM, or simply attaching a shadow DOM to any element on the page and programmatically adding html/elements to it via JavaScript.
We can also do it declaratively without any JavaScript as follows:
span {
background: yellow;
}
<div>
<template shadowrootmode="open">
<span>I'm a span in the shadow DOM</span>
</template>
</div>
<span>I'm a span outside the shadow DOM</span>
Upvotes: 0
Reputation: 1532
You could look into the all
property, and do something like:
var guesses_div = document.createElement("div");
guesses_div.style.all = "unset";
guesses_div.style.position = "fixed";
guesses_div.style.right = "0";
guesses_div.style.bottom = "0";
guesses_div.style.backgroundColor = "rgb(255, 255, 0)";
Unfortunately this does not work in IE or Safari yet, but as you're using Greasemonkey (only available for Firefox, I believe), you should be fine.
Upvotes: 0
Reputation: 195
How about inserting an iframe
instead of div
? iframe
will not inherit style from its parent.
If in doubt how to do that please refer to this question.
Upvotes: 0
Reputation: 73251
Not sure if it's the nicest way ever to do things, but in html5 you can use close to everything as tag name - so to not let your div inherit the sites css rules for a div, simply don't create a div
, but myDiv
for example
var guesses_div = document.createElement("myDiv");
guesses_div.style.position = "fixed";
guesses_div.style.right = "0";
guesses_div.style.bottom = "0";
guesses_div.style.backgroundColor = "rgb(255, 255, 0)"
Upvotes: 1
Reputation: 85565
Short answer: No. There is no way to prevent the inherited css.
Long answer: Yes. You should manually override the inherited css rules.
Upvotes: 2