Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte: styling the child component from parent component without using :global

In a parent component I am passing down a CSS class to child component.

Parent.svelte

import Child from .Child

<div class="parent-component-class">  
   <Child childClass="child-component-class">
</div>

Child.svelte

export let childClass;

<div class={childClass}></div>

I want to be able to style the child-component-class in the <style> tag of a parent component. The only way I found how to do it is using a "global" prefix:

<style lang="scss">
:global(.child-component-class) {
  /* some styles */
}
</style>

But that is not what I want. I want the styling to stay scoped inside the component Parent and down to it's child components. Any suggestions?

like image 937
mirta Avatar asked Oct 30 '25 08:10

mirta


1 Answers

That usually is not an issue if you have an element container, you can just use its scoping to ensure that everything is scoped overall.

.parent-component-class :global(.child-component-class) { ...

If you do not already have one and it would interfere with layout, you can usually use display: contents to avoid that.

By the way, if you want a property named class on your components, you can do this:

// Svelte 5
let { class: className = '' } = $props();

// Svelte 3/4
let className = '';
export { className as class };
like image 130
H.B. Avatar answered Nov 01 '25 07:11

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!