通常,你需要影响子组件内的样式。也许我们想把这些框变成红色、绿色和蓝色。
¥Often, you need to influence the styles inside a child component. Perhaps we want to make these boxes red, green and blue.
一种方法是使用 :global CSS 修饰符,它允许你不加区分地定位其他组件内的元素:
¥One way to do this is with the :global CSS modifier, which allows you to indiscriminately target elements inside other components:
<style>
.boxes :global(.box:nth-child(1)) {
background-color: red;
}
.boxes :global(.box:nth-child(2)) {
background-color: green;
}
.boxes :global(.box:nth-child(3)) {
background-color: blue;
}
</style>但有很多理由不这样做。首先,它非常冗长。另一方面,它很脆弱 - 对 Box.svelte 实现细节的任何更改都可能破坏选择器。
¥But there are lots of reasons not to do that. For one thing, it’s extremely verbose. For another, it’s brittle — any changes to the implementation details of Box.svelte could break the selector.
但最重要的是,这很粗鲁。组件应该能够自己决定哪些样式可以从 ‘outside’ 控制,就像它们决定哪些变量作为 props 公开一样。:global 应该被用作应急方案 - 最后的手段。
¥Most of all though, it’s rude. Components should be able to decide for themselves which styles can be controlled from ‘outside’, in the same way they decide which variables are exposed as props. :global should be used as an escape hatch — a last resort.
在 Box.svelte 内部,更改 background-color 以使其由 CSS 自定义属性 确定:
¥Inside Box.svelte, change background-color so that it is determined by a CSS custom property:
<style>
.box {
width: 5em;
height: 5em;
border-radius: 0.5em;
margin: 0 0 1em 0;
background-color: var(--color, #ddd);
}
</style>任何父元素(例如 <div class="boxes">)都可以设置 --color 的值,但我们也可以在单个组件上设置它:
¥Any parent element (such as <div class="boxes">) can set the value of --color, but we can also set it on individual components:
<div class="boxes">
<Box --color="red" />
<Box --color="green" />
<Box --color="blue" />
</div>值可以是动态的,就像任何其他属性一样。
¥The values can be dynamic, like any other attribute.
此功能的工作原理是将每个组件用
display: contents元素(需要时)封装起来,并将自定义属性应用于该元素。如果你检查这些元素,你会看到如下标记:
> <svelte-css-wrapper style="display: contents; --color: red;">
> <!-- contents -->
> </svelte-css-wrapper>
> ```
> 由于 `display: contents`,这不会影响你的布局,但额外的元素可能会影响 `.parent > .child` 等选择器。<script>
import Box from './Box.svelte';
</script>
<div class="boxes">
<Box />
<Box />
<Box />
</div>