如何在不将scoped放在style标记上的情况下将css范围化为div



我迫切需要将我的css范围界定为特定的div。

我想要的是,让我在某个div内的样式只影响该div内的任何东西,而不影响它之外的任何东西

示例:

        <style>
            p {
                color: red;
            }
        </style>
        <div class="global">
            <p>I am styled by the global styling!</p>
        </div>
        <div class="scoped">
            <style>
                p{
                    color: blue;
                    background: green;
                }
            </style>
            <p>These scoped styles do not affect the global styles</p>
        </div>

我知道将scope放在style标记上,但浏览器支持还远远不能达到实际用途。

正因为如此,我想知道是否有其他方法可以实现这一点,比如JavaScript?

谢谢!

编辑:

我不想通过在它前面放一个类来确定它的范围,比如.scoped p。我需要它是动态的,但我不能把.scoped放在所有标签前面。

使用CSS类怎么样?例如:

/* This only applies to p inside div with class 'global' */
div.global p {
    color: red;
}
/* This only applies to p inside div with class 'scoped' */
div.scoped p{
    color: blue;
    background: green;
}

如果您希望所有p都具有全局样式,并且仅作用域具有单独样式,请保持p规则不变,并创建作用域规则:

/* This rule applies to all p elements */
p {
    color: red;
}
/* This style overrides style of p inside div with class 'scoped' */
div.scoped p{
    color: blue;
    background: green;
}

分别选择每个类:

.global p {
    color: red;
}
.scoped p{
    color: blue;
    background: green;
}

相关内容

最新更新