0
0
Svelteframework~5 mins

Script, markup, and style sections in Svelte

Choose your learning style9 modes available
Introduction

Svelte uses three parts to build a component: script for logic, markup for structure, and style for look. This keeps things clear and organized.

When you want to add JavaScript code to control your component's behavior.
When you need to write the HTML structure that users will see.
When you want to style your component with CSS that only applies there.
When you want to keep your component's code clean and easy to understand.
When you want styles that don't affect other parts of your app.
Syntax
Svelte
<script>
  // JavaScript code here
</script>

<!-- HTML markup here -->

<style>
  /* CSS styles here */
</style>

The <script> section holds JavaScript logic like variables and functions.

The markup is plain HTML but can use Svelte features like curly braces for variables.

Examples
This example shows all three sections: script defines a variable, markup uses it, and style changes the button look.
Svelte
<script>
  let count = 0;
</script>

<button on:click={() => count++}>
  Clicked {count} times
</button>

<style>
  button {
    font-size: 1.2rem;
  }
</style>
Here, script sets a name, markup shows it inside a heading, and style colors the heading.
Svelte
<script>
  let name = 'Friend';
</script>

<h1>Hello {name}!</h1>

<style>
  h1 {
    color: teal;
  }
</style>
Sample Program

This Svelte component shows how script, markup, and style work together. The script holds a message and a function to change it. The markup displays the message and a button that calls the function when clicked. The style makes the text and button look nice and accessible.

Svelte
<script>
  let message = 'Welcome to Svelte!';
  function changeMessage() {
    message = 'You clicked the button!';
  }
</script>

<main>
  <h2>{message}</h2>
  <button on:click={changeMessage} aria-label="Change message">
    Click me
  </button>
</main>

<style>
  main {
    font-family: system-ui, sans-serif;
    text-align: center;
    margin-top: 2rem;
  }
  h2 {
    color: #2c3e50;
  }
  button {
    background-color: #42b983;
    border: none;
    padding: 0.5rem 1rem;
    color: white;
    font-size: 1rem;
    border-radius: 0.3rem;
    cursor: pointer;
  }
  button:hover,
  button:focus {
    background-color: #369870;
    outline: none;
  }
</style>
OutputSuccess
Important Notes

The <style> section styles only this component by default, avoiding conflicts.

Use on:click to handle user clicks in markup.

Always add aria-label or other accessibility attributes to interactive elements.

Summary

Svelte components have three parts: script for logic, markup for structure, and style for appearance.

This separation helps keep code clean and easy to manage.

Styles inside a component apply only there, making your app easier to maintain.