October 23, 2024
Chicago 12, Melborne City, USA
HTML

Isolate styles within a div


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.

Demo:

<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>
/* 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>

JS Fiddle: https://jsfiddle.net/nuwm9fpa/



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video