Svelte:没有全局唯一名称的样式特定元素

Svelte: style particular element without a globally unique name

我可以在下面使用什么 css 选择器来仅定位外部 div?

<div>
    <div>...</div>
    <div>...</div>
</div>

<style>
    OUTER.DIV.ONLY {
        background: url(outer.png);
    }
</style>

或者,我很高兴知道是否有一种方法可以使用 局部作用域 名称来命名外部 div,并且不会添加任何内容编译后的苗条。

我不能只添加 class="outer",因为这很可能与现有样式表发生冲突。

我可以添加 class="outer-au9a8bo9u" 但这很笨拙,尤其是因为 class 会向 svelte 编译器输出添加无用的字节。

我发布这个是希望有比这更优雅、更高效的东西。

你可以用CSS解决这个问题:

div:not(div > div)

字面意思 'a div that is not the child of another div'。不完全是最漂亮的选择器,但它确实有效。

更新

由于(我怀疑)not 内的选择器没有作用域的错误,上述内容似乎并不总是有效。 (bug report

作为替代方案,您可以扭转逻辑:

/* adds background everywhere */
div {
  background-image: url(...);
}
/* remove again from children */
div div {
  background-image: unset;
}