Home > other >  How to define CSS fields based on props in a Svelte component?
How to define CSS fields based on props in a Svelte component?

Time:01-02

I new to Svelte and interesting to conditional styling based on props. I have two Svelte components - Parent and Child, just for understanding.

The parent passes props to child - the pt property which should be the padding-top field of child's css. The Parent code looks like:

<script>
  import Child from "./Child.svelte";
</script>

<Child pt="45px" />

The Child component has two styles: padding-top and padding-bottom. Depending on what props are passed, the corresponding fields of styles are created. If no props is passed, then the component will have no styles. In the following example, we passed only the pt props which activates padding-top field:

<script>
  export let pb, pt;
  let styles = "";
  if (pt) styles  = "--pt:"   pt;
  if (pb) styles  = "--pb:"   pb;
</script>

<div  style={styles}>
  <h3>Hello</h3>
</div>

<style>
  .child {
    padding-top: var(--pt);
    padding-bottom: var(--pb);
  }
</style>

Everything works, but is this the right way? Or is there a more effective implementation of this task? Thanks for attension.

CodePudding user response:

Svelte has a built-in way to pass css variables to a component, called --style-props

You're write:

<Child --pt="45px" />

and this sets the css variable --pt to 45px

CodePudding user response:

Personally, I try to avoid specific styling properties and use utility classes for layout.

If a component may need styles or classes, properties can be exposed with empty default ''.

<script>
    export let style = '';
    let className = '';
    export { className as class }; // Necessary because `class` is a keyword
</script>

<div class={className} {style}>
    ...
</div>

Then utility classes, either from something like Tailwind or self-made, can be applied for layout, e.g.:

<Child  />

CodePudding user response:

<script>
  export let pb, pt;
</script>

<div  style:padding-top={pt} style:padding-bottom={pb}>
  <h3>Hello</h3>
</div>

More info:

  • Related