Limit scope of external css to only a specific element?

Solution 1:

UPDATE Support for this feature has been dropped. Please seek other options

Original Post:

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.

Solution 2:

Simply wrap all you css code inside the selector for parent element, say it's a div with id of foo you'd do the following:

div#foo{
//All your css
}

And convert it as less to css, it will prepend the right selectors. Note that you'll need to take care manually of things like @media queries and so on.

Solution 3:

While writing this, the <style scoped> is deprecated by the Chrome team. As a result I experimented with some approaches and released https://github.com/thgreasi/jquery.scopeLinkTags . Note: you should only have to use this approach in case that you can't control the imported CSS file. If you can use SASS/LESS/anything to pre-process your CSS, you should prefer that.

Solution 4:

A simple way is adding pre-class before all selector in css file.

I find a grunt script can do this:

https://github.com/ericf/grunt-css-selectors