I am needing an approach where I can scope CSS files to a certain portion of the page. In theory, this example should do what I need:
<html>
<head>
</head>
<body>
<div>
<style scope>
@import url("style1.css");
</style>
<div class="testText">Test with Style 1</div>
</div>
<div>
<style scope>
@import url("style2.css");
</style>
<div class="testText">Test with Style 2</div>
</div>
</body>
</html>
However, I found out that the scope element is only available in some browsers right now (Firefox 21+ mainly). So, I'm looking for a lazy way out or a problem. I need to integrate some content with different styles into a site. We tried loading both css filesets, but there are some style names that appear in both stylesheets, so it will be a lot of work to rename the style names in one fileset and in the corresponding html content, specially because you cannot just refactor with Eclipse... :)
Is there any other solution that can render such a result that is widely compatible?
Regards
Scoped styles aren't well-supported at this point and are going to cause you problems if you're expecting any sort of cross-browser coverage.
The only way you can really achieve what you're after is to use a unique classname (or ID) for each 'section' and then use inheritance to sort-of namespace your CSS. So if you want to target one specific section of the page, give it's parents a classname (eg: class="testone"
) and then make sure that any styles you want to apply to that section are appended with that classname:
.testone .title{...}
.testone h1{...}
.testone a{...
etc.
Failing that, there is also a jQuery-based scope polyfill which should give you a more browser-independent way of working with scoped CSS. It isn't something I've worked with so don't have any experience to offer, but it looks very promising from the few moments I've spent with it!
Do remember that as with any JavaScript-based solution like this one, anyone who loads your page without JavaScript enabled isn't going to get those little extra niceties so it's important to ensure that the page still behaves in an acceptable manner even when JS is disabled.
The attribute name in HTML5 drafts is scoped
, not scope
.
Support to it is slowly being implemented, but there is little reason to use the attribute, or scoped style sheets. Most browsers will take <style scoped>
simply as <style>
and apply it to the entire document.
Thus, it is best to analyze the problem you are trying to solve and find a different approach to it. In many cases, it is trivial, using suitable contextual selectors. Assign an id
attribute to an element and use an id selector as the first component of selectors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With