How to target a component in svelte with css?

The only way I can think of is with an additional div element.

App.svelte

<script>
    import Nested from './Nested.svelte'    
</script>

<style>
    div :global(.style-in-parent) {
        color: green;
    }
</style>

<div>
    <Nested />  
</div>

Nested.svelte

<div class="style-in-parent">
    Colored based on parent style
</div>

Multiple Nested elements

You could even allow the class name to be dynamic and allow for different colors if you use multiple Nested components. Here's a link to a working example.


You need to pass props to the parent component with export let, then tie those props to class or style in the child component.

You can either put a style tag on the element in the child you want to style dynamically and use a variable you export for the parent to determine the value of a style directly, then assign the color on the tag like this:

<!-- in parent component -->

<script>
import Nested from './Nested.svelte';
</script>

<Nested color="green"/>
<!-- in Nested.svelte -->

<script>
export let color;
</script>

<p style="color: {color}">
    Yes this will work
</p>

Upside here is flexibility if you only have one or two styles to adjust, downside is that you won't be able to adjust multiple CSS properties from a single prop.

or

You can still use the :global selector but just add a specific ref to the element being styled in the child like so:

<!-- in parent component -->

<script>
import Nested from './Nested.svelte';
</script>

<Nested ref="green"/>

<style>
:global([ref=green]) {
    background: green;
    color: white;
    padding: 5px;
    border-radius: .5rem;
}
</style>
<!-- in Nested.svelte -->

<script>
export let ref;
</script>

<p {ref}>
    Yes this will work also
</p>

This ensures global only affects the exact ref element inside the child it's intended for and not any other classes or native elements. You can see it in action at this REPL link