0
0
Svelteframework~30 mins

Passing styles to components (--style-props) in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Passing styles to components (--style-props) in Svelte
📖 Scenario: You are building a simple Svelte app that shows colored boxes with text. You want to pass different background colors and font sizes as styles from the parent component to child components.
🎯 Goal: Create a Svelte component that accepts style properties from its parent using --style-props technique and apply those styles dynamically.
📋 What You'll Learn
Create a child component with a style attribute that uses passed style props
Pass style properties like background-color and font-size from the parent
Use Svelte syntax for props and style binding
Render multiple child components with different styles
💡 Why This Matters
🌍 Real World
Passing styles as props is common when building reusable UI components that need to look different in different places without duplicating code.
💼 Career
Understanding how to pass and apply styles dynamically in components is essential for frontend developers working with modern frameworks like Svelte.
Progress0 / 4 steps
1
Create the Child Component with a Text Box
Create a Svelte component file named ColorBox.svelte. Inside it, create a <div> with the class box that displays the text {text}. Declare a prop called text to receive this text.
Svelte
Hint

Use export let text; to declare a prop in Svelte.

2
Add a Style Prop for Background Color
In ColorBox.svelte, add a new prop called bgColor to receive a background color. Add a style attribute to the <div> that sets background-color to {bgColor}.
Svelte
Hint

Use export let bgColor; and bind it in the style attribute.

3
Add Font Size Style Prop
In ColorBox.svelte, add a new prop called fontSize to receive font size. Update the style attribute on the <div> to also set font-size to {fontSize}. Use a semicolon to separate styles.
Svelte
Hint

Add export let fontSize; and include it in the style attribute separated by a semicolon.

4
Use the Child Component with Different Styles
In App.svelte, import ColorBox from ./ColorBox.svelte. Render three <ColorBox> components with these props:
1. text="Red Box", bgColor="red", fontSize="1.5rem"
2. text="Green Box", bgColor="green", fontSize="2rem"
3. text="Blue Box", bgColor="blue", fontSize="1rem"
Svelte
Hint

Use the <ColorBox> component with the exact props given.