8

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 class="child" 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.

3 Answers 3

6

Svelte has a built-in way to pass CSS variables to a component through what's called:
--style-props

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

This sets the css value of var(--pt) to 45px

Sign up to request clarification or add additional context in comments.

2 Comments

(This also creates a wrapper element which can mess up layout.)
True, but caniuse.com/css-display-contents support is quite good (as long as you don't use IE11 )
6
<script>
  export let pb, pt;
</script>

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

More info:

Comments

2

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 class="pt32" />

2 Comments

(This disables svelte's detection to see which classes written in the <style> block are unused)
True, there are always some trade-offs 😅

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.