0
0
Svelteframework~5 mins

Passing styles to components (--style-props) in Svelte

Choose your learning style9 modes available
Introduction

Passing styles to components lets you change how they look without changing their code. It helps you reuse components with different colors, sizes, or fonts easily.

You want to reuse a button component but with different background colors.
You need to adjust the font size of a text component in different places.
You want to add margin or padding to a component without editing its internal styles.
You want to change the border style of a card component depending on the page.
You want to keep your components clean and style them from outside.
Syntax
Svelte
<Component style="property: value;" />
Use the style attribute to pass CSS styles directly to a component.
Inside the component, use export let style = ''; to accept the style string.
Examples
This passes a blue background and white text color to the Button component.
Svelte
<Button style="background-color: blue; color: white;" />
This adds a red border and padding to the Card component.
Svelte
<Card style="border: 2px solid red; padding: 1rem;" />
This makes the Text component bigger and bold.
Svelte
<Text style="font-size: 1.5rem; font-weight: bold;" />
Sample Program

This example shows a simple component that accepts a style prop. The styles passed from outside are applied to the div. The usage example passes a light green background, padding, and rounded corners.

Svelte
<script>
  export let style = '';
</script>

<div style={style} aria-label="Styled box">
  This box uses passed styles.
</div>

<!-- Usage example -->

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

<StyledBox style="background-color: lightgreen; padding: 1rem; border-radius: 0.5rem;" />
OutputSuccess
Important Notes

Always use semantic HTML and add ARIA labels for accessibility.

Passing styles as strings works well for simple style changes.

For complex styling, consider using CSS variables or class props.

Summary

Passing styles lets you customize components without changing their code.

Use the style attribute and accept it as a prop inside the component.

This keeps components reusable and flexible.