kaxi1993 kaxi1993 - 1 year ago 53
CSS Question

how to protect embedded div style not to be overridden by website style

I have div with its own style. I embedded this div on other website.

<div id="scoped-div">
<style>
label {
color: green;
}
</style>

<label> Scoped div </label>
</div>


But I face problem, my div style is overridden by website style. I don't want to use
iframe
. Except for the use of
iframe
is there any other way to protect my div style by external style changes?

Answer Source

Your request is exactly what Shadow DOM makes possible:

  1. attach a Shadow DOM to the element you want to protect (here: #scope-div),
  2. put the HTML code you want to protect in the Shadow DOM,
  3. clone it from a <template> element to get it easy (optional).

That's it!

var div = document.querySelector( "#scoped-div" )
var template = document.querySelector( "template" )

var sh
if ( 'attachShadow' in div )
  sh = div.attachShadow( { mode: "closed" } )  //Shadow DOM v1
else
  sh = div.createShadowRoot()                 //Shadow DOM v0 fallback

sh.appendChild( template.content.cloneNode( true ) )
<template>
  <style>
    label {
      color: green;
    }
  </style>

  <label> Scoped div </label>
</template>

<div id="scoped-div">
</div>