Home > OS >  How can I disable all CSS that can affect my widgets on another website?
How can I disable all CSS that can affect my widgets on another website?

Time:10-11

I'm building JavaScript widgets that are supposed to be added onto other people's websites.

I style my widgets by dynamically adding a CSS to the pages they're on.

For example,

My CSS code below applies to a DIV inside my widget:

.myWidget { background-color: red; }

But a CSS file outside my own on a remote page might have:

div { border: 5px solid green; }

The CSS above would also apply to my widgets. How can I disable all other CSS outside my own?

Thanks

CodePudding user response:

You could be Using shadow DOM

Shadow DOM MDN Web Docs

An important aspect of web components is encapsulation — being able to keep the markup structure, style, and behavior hidden and separate from other code on the page so that different parts do not clash, and the code can be kept nice and clean. The Shadow DOM API is a key part of this, providing a way to attach a hidden separated DOM to an element.

CodePudding user response:

You can use the all shorthand property and the unset keyword to set each property's value to its initial value.

.myWidget {
  all:unset;
  background-color: red;
}

div {
  background-color:yellow;
}
<div class="myWidget">Hello World!</div>

  • Related