SnareChops SnareChops - 5 months ago 109
CSS Question

Limit scope of external css to only a specific element?

I am creating a mobile simulator that mocks the appearance and functionality of an iPhone (and other devices later) in a web browser, using 100% javascript, HTML5, and CSS, with the simulator fully functional with only client side code.

While trying to accomplish this task with as little modification as necessary to the original app projects themselves to be hosted in the simulator, I am injecting the

<script>
and
<link>
tags into the head of the page, then loading the html into a
<div>
screen.

The problem is that when I load in a new css file, it (obviously) overrides the one I'm using to style the page, and therefor some elements are affected (ex the background changes color).

My question is: Is there any way to limit the "scope" of an external
.css
file to apply only to objects within the
<div>
screen? Would it make any difference if instead of me injecting it into the
<head>
of the page, I inject it into a
<style>
element in the
<div>
screen?

Simulator project at http://github.com/BluelineApps/iOSSimulator (code for this injection is in the
Replaceiframe
branch,
js/simulator.js
if needed)

Thank you, and all ideas welcome.

Answer

You may want to look at scoped styles; see http://css-tricks.com/saving-the-day-with-scoped-css/.

The basic idea is

<div>
    <style scoped>
        @import "scoped.css";
    </style>
</div>

However, you are on the bleeding edge here in terms of browser support. See http://caniuse.com/style-scoped.

One alternative would be to use an iframe.