Reputation: 14062
I'm trying to pass an additional class to a component through a custom property but the compiler detects that the class is not in use and does not include it. Given this component:
<script>
import {createEventDispatcher} from 'svelte';
const dispatch = createEventDispatcher();
export let imageUrl = null;
export let cssClass = '';
export let data = null;
function handleImageClick(e){
dispatch('press', {element:this, event: e, props: $$props });
}
</script>
<style>
.image-button{
width:100px;
height: 72px;
}
</style>
<div class="image-button {cssClass}" on:click={handleImageClick} style="background:url({imageUrl});background-size: cover;"></div>
I create an instance like this and pass it my additional class through the cssClass prop:
<script>
import ImageButton from './components/ImageButton.svelte';
let imgUrl = "/images/test.png";
</script>
<style>
.my-image-button{
border: 1px solid white;
}
</style>
<ImageButton imageUrl={imgUrl} cssClass="my-image-button" />
The ImageButton instance is created and it has the additional "my-image-button" class but the style rule I declared in .my-image-button is not included. Is there a way to force the compiler to include a style rule or another workflow to enable this functionality?
Upvotes: 3
Views: 1599
Reputation: 29585
In the parent component, change .my-image-button
to :global(.my-image-button)
. That way, Svelte will know that it needs to preserve that selector.
If you want to ensure that the CSS only applies to elements with that class inside the component where the styles are declared, you can use a wrapper element:
<div>
<ImageButton .../>
</div>
<style>
div :global(.my-image-button) {
/* ... */
}
</style>
Upvotes: 7