0
0
Svelteframework~30 mins

Scoped styles by default in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Scoped styles by default in Svelte
📖 Scenario: You are building a simple user profile card for a website. You want to style the card so that the styles only apply to this card component and do not affect other parts of the page.
🎯 Goal: Create a Svelte component with scoped styles so that the styles apply only inside this component.
📋 What You'll Learn
Create a Svelte component with a <script> section containing a user object with name and age properties.
Add a configuration variable called highlightAge set to 30.
Use a Svelte reactive statement to create a variable isHighlighted that is true if user.age is greater than highlightAge.
Add scoped CSS styles inside a <style> tag that style the card and highlight the age if isHighlighted is true.
💡 Why This Matters
🌍 Real World
Scoped styles help keep component styles isolated so they do not affect other parts of a web page. This is useful in large web apps with many components.
💼 Career
Understanding scoped styles and reactive variables in Svelte is important for building maintainable and bug-free user interfaces in modern web development.
Progress0 / 4 steps
1
Create the user data
Create a user object inside the <script> tag with name set to "Alice" and age set to 35.
Svelte
Need a hint?

Use const user = { name: "Alice", age: 35 } inside the <script> tag.

2
Add a highlight age configuration
Add a constant variable called highlightAge inside the <script> tag and set it to 30.
Svelte
Need a hint?

Write const highlightAge = 30; inside the <script> tag.

3
Create reactive variable for highlighting
Add a reactive statement that creates a variable isHighlighted which is true if user.age is greater than highlightAge, otherwise false. Use $: syntax inside the <script> tag.
Svelte
Need a hint?

Use $: isHighlighted = user.age > highlightAge; to create a reactive variable.

4
Add scoped styles with conditional class
Add a <style> tag with scoped CSS that styles the .card with a border and padding. Also add a style for .is-highlighted that changes the text color to red. Use the class directive class:is-highlighted={isHighlighted} on the age paragraph.
Svelte
Need a hint?

Write CSS inside <style> to style .card and .is-highlighted. Use the class directive on the age paragraph.