为div和所有子节点设置不同的样式表?

时间:2013-02-19 13:38:38

标签: css stylesheet encapsulation

我想知道是否有可能使div忽略文档中的所有css规则,而是为自己及其所有子节点使用不同的样式表。

一个小例子:

<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>

如您所见,我想直接在div上定义样式表,而不是全局。有没有办法做这样的事情?

我想要实现的是对代码的更多封装。我知道还有像伪命名空间这样的可能性,但这很丑陋,但仍不能保证没有冲突......

更新

与此同时,我发现了样式元素的“范围”属性,它与我的要求非常相似。但它几乎没有浏览器支持。

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:3)

如果没有<style scoped>属性,您将无法执行此操作。而且,正如你所说,这是非常不受支持的。 GitHub上的This is a jQuery plugin for scoped styles,它推动了对更多浏览器的支持。您还可以使用此jQuery插件在您的作用域样式定义中@import other-stylesheet.css

但考虑到所有事情,你可能最好在一个元素上使用多个类。给一个div几个类,你可以相当合理地组织你的项目。像<div class="parent child grandchildren-1">这样的东西只能由这个css选择:

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