Search code examples
cssstylesheetencapsulation

Set different stylesheet for div and all child-nodes?


I'm wondering if there is a possibility to make a div ignore all css rules in the document and instead using a different stylesheet for itself and all of its child nodes.

A little example:

<html>
    <head>
        <style>
            div{color:red}
        </style>
    </head>
    <body>
        <div>This is red text</div>
        <div stylesheet="/path/to/my/stylesheet.css">
            This is text in a color defined in the other stylesheet
            <div>This is also not red</div>
        </div>
    </body>
</html>

As you can see, I want to define a stylesheet directly onto a div, and not globally. Is there a way to do something like that?

What I want to achieve is more encapsulation of my code. I know there also possibilities like pseudo-namespacing, but that's ugly as hell and still does not guarantee that there are no conflicts...

Update

In the meantime, I've found the "scoped" attribute of style elements, which does a very similar thing to what I requested. But it's supported by almost no browser.

Are there better solutions?


Solution

  • You won't be able to do this without a <style scoped> attribute. And, as you said, that is horribly unsupported. This is a jQuery plugin for scoped styles on GitHub, and it pushes support for a lot more browsers. You'd also be able to @import other-stylesheet.css in your scoped style definition with this jQuery plugin.

    All things considered though, you might actually be better off using multiple classes on one element. Give a div a couple of classes, and you can organize your projects fairly decently. Something like <div class="parent child grandchildren-1"> would only be selected by this css:

    .parent.child.grandchildren-1 { color:red; }