DEV Community

Cover image for One weird trick! (To encapsulating your CSS)
Michael Solati
Michael Solati

Posted on • Edited on • Originally published at michaelsolati.com

2

One weird trick! (To encapsulating your CSS)

Web developers are going to hate me, cause this is an interesting solution...

Need to encapsulate the CSS of some HTML5? Well you can use an <iframe> to embed your HTML into a page without the rest of the page's CSS affect it using the srcdoc property!

Why would you want to do this? Well I'm currently working on including the content of the newsletters we email out on web.dev on the website. However they all have their own custom styling that we don't want the CSS of the site to conflict them.

An <iframe> would allow us to encapsulate the styling so that there is no conflict, but it would be gross to point the <iframe> to another URL on the site as we would need another network request in order to render the page (and a search engine could crawl the embedded URL, which we wouldn't want to surface). So the easy solution was to use srcdoc to dump the HTML of a newsletter into the <iframe> without requiring another network request, or for another page to exist somewhere!


To keep up with everything I’m doing, follow me on Twitter. If you’re thinking, “Show me the code!” you can find me on GitHub.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →