I have some sitewide styles and some custom styles, and I want the site wide styles to not apply to the div with id custom-styles
or any of its containing elements. How can this be achieved without having to change the CSS in the site wide styles?
I’ve tried adding style="all: unset;"
to the div (i.e. #custom-styles, #custom-styles * {all: unset}
), but to no avail. Ideally I’d like any styles inside the custom styles div to not inherit any styles from anywhere in case they mess anything up.
To give some context, users need to be able to add their own CSS, and it along with some custom HTML will be inserted on their websites, hence I don’t want any of their website styles to affect the styles of the custom HTML. I can to some extent control the custom HTML, e.g. by wrapping their custom HTML inside my own div with an id or class that I can add my own styles to.
<style>
/* sitewide styles */
*,
::before,
::after {
margin: 0.5em;
padding: 0.5em;
border: none;
box-sizing: inherit;
font-family: 'Arial';
}
p {color: red !important}
</style>
<p>
This should be red with all the default styles
</p>
<div id='custom-styles' style="all: unset;">
<style>
/* custom styles for this div only */
p {color: green;}
</style>
<p>
I want this (and any other element within this div) to not be red and not have any default styles - it should only have the styles inside the second style tag (and, for example, be green)
</p>
</div>
2
Answers
I recommend avoiding inlining styles in this manner.
The
all: unset
rule does not affect inherited properties unless they are explicitly reset.I would also use a class for this, not an ID. This way it’s more portable.
If you want to be less destructive, I recommend only using important when you can’t control the specificity like in the case where the global
<p>
color is forced to be red.If you want a particular element and it’s content to ignore all CSS declared on the page, try using the shadow DOM. All elements within the shadow DOM are only affected by CSS declared within the shadow DOM. There is an exception concerning inherited styles from CSS declared within the regular DOM, (see comments in the HTML marked with a ❉ for the solution).
The example below uses a
<template>
to populate the shadow DOM and declare CSS within the shadow DOM. Details are commented in the example.