Presented here is a straightforward component called Text.svelte
. It utilizes a CSS variable to prevent unnecessary duplication:
<div>
<span class="t1">t1</span> <span class="t2">t2</span>
</div>
<style>
:root {
--color: #f08080;
}
.t1 {
border: solid var(--color);
}
.t2 {
color: var(--color);
}
</style>
While this component functions properly on its own, it can encounter issues if a parent component also defines the --color
variable. This could lead to undesired overrides. Take a look at App.svelte
:
<script>
import Text from './Text.svelte';
</script>
<Text/>
<div>app</div>
<style>
:root {
--color: #00ff00;
color: var(--color);
}
div {
border: solid 5px var(--color);
}
</style>
Check out the Svelte repl for a live example:
In the Svelte repl, instances of --color
are highlighted in red, but when running it locally, they appear green. What errors may I be making here, and what other options exist? Perhaps defining CSS variables within :root
blocks in components is not advisable.