Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit scope of external css to only a specific element?

Tags:

html

css

People also ask

What are external rules in CSS?

An external style sheet is simply a listing of CSS rules. It cannot contain HTML tags. The <link> tag, which goes in the head of an HTML page, is used to link to an external style sheet. There is no limit to the number of external style sheets a single HTML page can use.

Is there any limit on CSS?

No , There won't be any limit.


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.


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.


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.


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


This is how i do it if not using preprocessor in my project. Search for a online preprocessor then load copy paste the css under the parent class/id

.parent{
    // copy paste here
}

Example

  1. Find a preprocessor for example https://beautifytools.com/scss-compiler.php works very well for me (I have no affiliation with the given link)
  2. if you are using from a URL add the URL using the load URL button.
  3. Wrap the css code under parent and hit compile then minify.

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!