Allows you to style elements inside a child component using similar syntax as CSS Shadow Parts.
Child.svelte
<div part>
<h1 part="heading">Child component!</h1>
</div>Parent.svelte
<script>
import Child from "./Child.svelte";
</script>
<Child />
<style>
Child {
padding: 8px;
}
Child::part(heading) {
font-size: 2rem;
}
</style>npm i -D svelte-preprocess-style-child-componentAdd preprocessor in svelte.config.js. Should be something like:
import { styleChildComponent } from "svelte-preprocess-style-child-component";
...
{
preprocess: [styleChildComponent(), preprocess()],
}<Card class="item" />
<OtherCard class="item" />
<style>
.item::part {
color: red;
}
</style>::part is not needed when targeting component
These are the same:
Child {
color: red;
}
Child::part {
color: red;
}NOTE: You cannot skip the ::part selector when using just a class selector.
<Child class="item" />
<Child />
<style>
.item {
/* Does not work */
color: red;
}
.item::part {
/* Works! */
color: red;
}
Child.item {
/* Works! */
color: red;
}
</style>It transforms component selectors to global selectors, and passes down the class to the Child component, that then applies it to the correct elements.
<div part>
<h1 part="heading">Child component!</h1>
</div>⬇️
<div class={$$props.parts$$?.default$$}>
<h1 class={$$props.parts$$?.heading}>Child component!</h1>
</div><script>
import Child from "./Child.svelte";
</script>
<Child />
<style>
Child {
padding: 8px;
}
Child::part(heading) {
font-size: 2rem;
}
</style>⬇️
<script>
import Child from "./Child.svelte";
</script>
<Child parts$$={{"default$$":"svelte-child-27gw8r","heading":"svelte-child-qzjtt3"}} />
<style>
:global(.svelte-child-27gw8r) {
padding: 8px;
}
:global(.svelte-child-qzjtt3) {
font-size: 2rem;
}
</style>I'm sure there are some! Please submit an issue if it doesn't work as expected!