How to Isolate a Div from Public CSS Styles

How To Isolate a div from public CSS styles?

CSS Cascading and Inheritance Level 3 introduces the all shorthand property and the unset keyword, which, together, allow you to achieve this conveniently.

For example, if an author specifies all: initial on an element it will
block all inheritance and reset all properties, as if no rules
appeared in the author, user, or user-agent levels of the cascade.

This can be useful for the root element of a "widget" included in a
page, which does not wish to inherit the styles of the outer page.
Note, however, that any "default" style applied to that element (such
as, e.g. display: block from the UA style sheet on block elements such
as <div>) will also be blown away.

You’ll need to apply all: initial to your div and all: unset to its descendants:

#mydiv {
all: initial; /* blocking inheritance for all properties */
}
#mydiv * {
all: unset; /* allowing inheritance within #mydiv */
}

You may want to use a class on your div instead of an id, so that any rules you write to style its descendants won’t have to match or beat the high specificity used in this rule.

To be really safe, you may want to block styles on potential pseudo-element descendants too:

#mydiv::before,
#mydiv::after,
#mydiv *::before,
#mydiv *::after {
all: unset;
}

Alternatively, for broader browser support, you can manually attempt to do what all does by setting all known CSS properties (don’t forget the prefixed versions):

#mydiv {
/*
* using initial for all properties
* to totally block inheritance
*/
align-content: initial;
align-items: initial;
align-self: initial;
alignment-baseline: initial;
animation: initial;
backface-visibility: initial;
background: initial;
...
}

#mydiv::before,
#mydiv::after,
#mydiv *,
#mydiv *::before,
#mydiv *::after {
/*
* using inherit for normally heritable properties,
* and initial for the others, as unset does
*/
align-content: initial;
align-items: initial;
align-self: initial;
...
color: inherit;
...
}

You can encourage browser support for the all shorthand property and track its adoption with these issue links:

  • ☑ Chrome 37+
  • ☑ Firefox 27+
  • ☑ Webkit (Safari 9.1+)
  • ☐ Internet Explorer
  • ☑ Edge 79+
  • ☑ Opera 24+

Up-to-date browser support information for the all shorthand property is available here.

How to Isolate a DIV and its contents from external CSS

Shadow DOM with scoped CSS seems to be a good solution. However, it's still not production-ready, lacks browser support.

I ended up using Cleanslate CSS. It adds an extra ~20KB CSS. But do the job really well. Support all browsers too.

How to isolate CSS rules inside a div?

This is just wrong.
An HTML document can only have one html tag and one body tag, otherwise it will be an invalid document, browsers won't allow it.

If you load an iframe, instead, it will have his own #document and it's fine.



Related Topics



Leave a reply



Submit