It is virtually impossible to stop CSS code from modifying your elements, as the web currently exists. What you are essentially talking about is sandboxing your elements, preventing them from being modified by other code.
You can do this with an iframe, but that's horrid and almost certainly too much faff.
On the other hand, the future is bright! There is a feature coming called the Shadow DOM, which essentially works to allow you to implement your own elements and sandbox them from the rest of your code. It's already how elements like input and video work behind the scenes: now we get to do what the browsers have been doing for years.
You can create an element: we'll call it solid-button.
<solid-button></solid-button>
We'll then write the code to go inside it. We'll put this in a template so it doesn't appear on the screen till we want it:
<template id="solid-button-src">
<style>
button {
width: 100px;
height: 100px;
background-color: green;
border: solid 1px black;
}
</style>
<button></button>
</template>
We then use a little bit of Javascript to create the Shadow DOM and add the content in the template into it:
customElements.define('solid-button', class extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({
mode: 'open'
});
const template = document.querySelector('#solid-button-src');
const clone = document.importNode(template.content, true);
shadowRoot.appendChild(clone);
}
});
This works in some browsers now, but nowhere near enough to make it production-ready. Your user can apply styles to solid-button, but they won't affect the content inside. If you have an up-to-date browser, you can see this in effect below.
Obviously this is not a solution for you now, but it might be the future.
customElements.define('solid-button', class extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({
mode: 'open'
});
const template = document.querySelector('template');
const clone = document.importNode(template.content, true);
shadowRoot.appendChild(clone);
}
});
button {
height: 100px;
width: 100px;
background-color: red;
border: solid 1px black;
}
.class1 {
height: 100px;
width: 100px;
background-color: blue;
}
my-button {
background: red; /* does nothing visible */
}
<button></button>
<button id="id1" class="class1"></button>
<solid-button></solid-button>
<solid-button class="class1"></solid-button>
<template>
<style>
button {
width: 100px;
height: 100px;
background-color: green;
border: solid 1px black;
}
</style>
<button>
<slot name="content"></slot>
</button>
</template>
important!