Ignore/override surrounding / inherited CSS

2019-08-19 16:56发布

I have this call to add HTML/CSS to an existing page:

let div = document.createElement('div');
div.style.zIndex = 9999999;
div.innerHTML = str;  // some pre-defined HTML string
document.body.insertBefore(div, document.body.firstChild);

I am creating a Chrome Extension that helps developers. What's happening is that the above HTML is inheriting the existing CSS from developer's pages. I want the styling of the above HTML to be independent from the CSS/styling on the developer's page.

Is there a way to ignore all existing CSS on page? I'd like to basically create a "CSS sandbox".

I think one way to create such a sandbox, would be an iframe, but I am looking for a simpler way to do that.

1条回答
再贱就再见
2楼-- · 2019-08-19 17:33

Add a class to elements which you want to reset..and then apply all:unset to that class

The all CSS shorthand property sets all of an element's properties (apart from unicode-bidi and direction) to their initial or inherited values, or to the values specified in another style sheet origin.


...all:unset

Specifies that all the element's properties should be changed to their inherited values if they inherit by default, or to their initial values if not.(It will ignore all the user agent style too.)

Stack Snippet

let p = document.createElement('p');
p.style.color = "red";
p.innerHTML = "Hello"; // some pre-defined HTML string
p.classList.add("reset");
document.body.insertBefore(p, document.body.firstChild);
p {
  background: black;
}

.reset {
  all: unset;
}

查看更多
登录 后发表回答