Are there any Chrome-specific techniques to scope/isolate CSS?

357 views Asked by At

I'm writing a Chrome extension that injects HTML into a displayed page. I want the injected HTML to have it's own style, protected from the CSS that may be present in the host page.

I've tried using conventional CSS, and still suffer from style corruption from the host page.

After watching the Polymer presentation from I/O 15, I was wondering if there are any new, Chrome-specific techniques that I can use to achieve this?

2

There are 2 answers

3
Ben Thomas On BEST ANSWER

What you will want to look into is shadow-dom. This will enable you to create a widget/component (which would be your injected html). This would mean that the DOM tree for the widget/component is encapsulated and no external styles from the page will affect it. There is a good article on html5rocks covering this. You may also want to look into WebComponents. Bear in mind that this functionality is only available in the latest browser versions.

3
Corey Trombley On

Two things that I currently use at my place of work are:

I use react at work, hence react-css-modules, but css-modules should work in your case. It's not Chrome specific, but we use them within the context of each component we build. Basically, like the docs state, a class of row would become something like table__row___2w27N. The breakdown of the built name is the filename of the CSS than the class name followed by a base64 hash of 5 char. I hope this helps.

One potential downside is Webpack would be required.

Here is an example of our component folder structure:

- component
  - Component.jsx/js
  - component.css/scss/sass
  - component.test.js