Svelte uses three parts to build a component: script for logic, markup for structure, and style for look. This keeps things clear and organized.
Script, markup, and style sections in 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.
<script> let count = 0; </script> <button on:click={() => count++}> Clicked {count} times </button> <style> button { font-size: 1.2rem; } </style>
<script> let name = 'Friend'; </script> <h1>Hello {name}!</h1> <style> h1 { color: teal; } </style>
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.
<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>
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.
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.