英文:
CSS classes in Svelte components could be accidentally overwritten
问题
Svelte支持作用域CSS,这意味着如果有一个类名,会添加一个额外的生成类名。例如:
<div class="item"></div>
会被转换成:
<div class="item item-poYXsoYvx1uy"></div>
并且样式将被应用为.item.item-poYXsoYvx1uy
以增加特异性。这是有益的。
但是想象一下,你正在使用Svelte构建一个小组件,并将其嵌入到某个页面中,而该页面上也使用了类名item
。这可能会轻松干扰你的小组件并破坏样式。
我更希望在生产构建中根本不保留初始类名,只保留散列类名。这是否可能?
英文:
Svelte has support for scoped CSS, means if there is a class, one more generated class will be added. For example:
<div class="item"></div>
will be transformed:
<div class="item item-poYXsoYvx1uy"></div>
and styles will be applied as .item.item-poYXsoYvx1uy
to increase specificity. It's good.
But imagine you building a widget using Svelte and embed it to some page where the class name item
used as well. It could easily interfere with your widget and brake styling.
I'd prefer not to have initial class names at all in the production build, just with hash ones. Is it possible?
答案1
得分: 1
你可以直接使用标签名称来定位元素,但这不会让你走得很远。
在与未经范围限定的样式一起使用组件可能会引发问题的情况下,我建议给类名加上前缀。
例如,使用.sc-item
(代表"Svelte组件")或类似/更独特的名称。
英文:
You can target elements directly using the tag name but that will not get you very far.
In a scenario where a component is used together with unscoped styles that could cause issues, I would recommend prefixing classes.
E.g. use .sc-item
(for "Svelte component") or something similar/more unique.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论