How To Isolate a div from public CSS styles?

后端 未结 5 1663
栀梦
栀梦 2020-11-27 13:44

i have some code for example here in html


 
  
  

Hi it\'s test

5条回答
  •  清酒与你
    2020-11-27 14:15

    iframe is also a decent solution for isolation of styles if it doesn't complicate other business logic. Plus this can be done in pure JavaScript and may work in older browsers too.

    const HTMLToIsolate = `...` // get your div tag as HTML string
    const parentContainerRef = document.body; // or something else
    const newIframe = document.createElement('iframe');
    // set height & width to 100% and remove borders for newIframe
    
    parentContainerRef.appendChild(newIframe)
    newIframe.contentWindow.document.open('text/html', 'replace');
    newIframe.contentWindow.document.write(HTMLToIsolate);
    newIframe.contentWindow.document.close();
    
    // bonus to remove scroll bars by setting proper iframe's height
    newIframe.addEventListener('load', function onIFrameLoad(e) {
        const iframeBody = this.contentDocument.querySelector("body");
        this.style.height = `${iframeBody.scrollHeight}px`;
    });
    

    This worked perfectly for me when I had to embed a complex HTML file into my webpage fetched remotely without MixedContent warning and without parent HTML styles overriding the embedded HTML. Thanks to https://benfrain.com/sandbox-local-htmlcss-code-snippets-inside-iframe-style-guidespattern-libraries/ for this excellent idea!

    Though #mydiv * { all: unset } CSS trick, as suggested in the accepted solution here works, it ended being a complex browser operation as there were many DOM nodes on my page.

提交回复
热议问题