This repo attempts to document the ways to have CSS encapsulation today.
In a drawing:
Use cases (the why):
- Re-using components across websites
- A component can be anything: a video player, a PDF viewer, a weather widget, an HTML5 ad
See the iframe/
folder.
An iframe in the most basic encapsulation method and since it's so old it works everywhere. Basically you are referencing a new HTML page inside the other one.
-
Advantages
- Easy to implement
- Works everywhere
-
Disadvantages
- 2 HTTP requests for the HTML
- The element container (iframe) doesn't scale with the page automatically
- Parent site can't touch what is happening in the frame
No example here. Basically you make sure styles don't touch other styles by prefixing everything and never using !important
and taking great care in specifity matters.
Scoped stylesheets are not a solution to CSS encapsulation. The only thing scoped styles does is limit styles to a particular element in the DOM. It doesn't prevent styles from the parent page to cascade to the "component".
See the style-scoped/
folder.
-
Advantages
- Easy to implement
-
Disadvantages
- Browser support is limited (there is a polyfill)
- Not a solution since styles bleed through
- Scoped styles - HTML5 for web designers
- Saving the Day with Scoped CSS by Arley McBlain
Possibly the best solution. What we actually want.
See the two demos in directories shadow-dom
and 'custom elements`.
-
Advantages
- Encapsulate styles OR provide hooks for styling to parent element (see Reaching into Shadows with CSS here)
-
Disadvantages
- Has to be polyfilled for now using Polymer
- Relatively unstable, everything is being developed as we speak
See Polymer project.