What is svelte:body in Svelte: Explanation and Usage
svelte:body is a special Svelte tag that lets you insert content directly into the HTML element outside your component's root. It is useful when you want to add global elements like modals or scripts that must be placed at the body level.How It Works
Imagine your Svelte component as a box that normally controls only what goes inside itself. But sometimes, you want to put something outside that box, directly into the main <body> of the page. This is where svelte:body comes in.
Using svelte:body is like having a special window that lets you place content anywhere inside the <body> tag, no matter where your component is mounted. This is helpful for things like modals, notifications, or scripts that need to be global and not confined inside your component's HTML structure.
It works by telling Svelte to render the enclosed content directly inside the document's <body>, bypassing the usual component boundaries.
Example
This example shows how to use svelte:body to add a modal overlay that appears at the body level, outside the main component structure.
<script> let showModal = false; </script> <svelte:body> {#if showModal} <div class="modal-overlay" on:click={() => showModal = false}> <div class="modal-content" on:click|stopPropagation> <p>This modal is rendered inside <body> using svelte:body.</p> <button on:click={() => showModal = false}>Close</button> </div> </div> {/if} </svelte:body> <button on:click={() => showModal = true}>Open Modal</button> <style> .modal-overlay { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .modal-content { background: white; padding: 1rem 2rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.3); } </style>
When to Use
Use svelte:body when you need to place elements directly inside the <body> tag instead of inside your component's root element. This is common for:
- Modals and overlays that should cover the entire viewport and not be constrained by parent containers.
- Global notifications or alerts that appear above all other content.
- Scripts or elements that require placement at the body level for proper behavior.
It helps keep your component code clean while managing global UI elements that must escape normal component boundaries.
Key Points
svelte:bodyinserts content directly into the HTML<body>tag.- It is useful for modals, overlays, and global UI elements.
- Content inside
svelte:bodyis outside the component's normal DOM tree. - Helps manage elements that must not be confined by component containers.
Key Takeaways
svelte:body lets you render content directly inside the HTML <body> element.svelte:body is not nested inside the component's root element.