Svelte 33 🧡 Element Dimensions and Scroll Position Bindings — bind:clientWidth, bind:scrollY
Layout and scroll awareness are fundamental to modern user interfaces, especially when building responsive components, floating headers, or infinite scrolling lists. Manually measuring elements via getBoundingClientRect() or calculating scroll offsets with window.addEventListener('scroll') creates significant performance overhead and messy, imperative code. Svelte simplifies this by providing specific, reactive bindings that bind element dimensions and scroll positions directly to your state variables.
This chapter covers the reactive binding directives for measuring DOM element dimensions and tracking scroll positions. We will explore how these read-only bindings update whenever the browser layout shifts or the user scrolls, allowing you to reactively control UI logic—such as sticky navigation bars or dynamic content loading—without needing to manually manage event listeners or timers.
Key point: Svelte’s dimension and scroll bindings provide a declarative, performance-optimized way to track DOM geometry by internally managing ResizeObserver and scroll event listeners, keeping your state perfectly synced with the rendered layout.
Why element and scroll bindings exist
The layout thrashing problem.
Manually measuring elements by querying the DOM (element.offsetWidth) frequently leads to “layout thrashing,” where the browser must re-calculate the CSS box model multiple times. Svelte optimizes these measurements within its update cycle.
The reactivity requirement.
Dynamic content can change an element’s size at any time. Bindings turn these changes into reactive state, ensuring that your logic—like hiding a menu when a screen gets too small—always operates on the correct values.
The scroll-event overhead.
Tracking window.scrollY manually requires an event listener that fires hundreds of times per second. Svelte’s bind:scrollY implementation is efficiently throttled, preventing performance degradation in your application.
The responsiveness gap.
Standard CSS handles many layout tasks, but logic often requires JavaScript-based measurements (e.g., checking if a container is wider than its content to show a scrollbar). Bindings expose this data without complex boilerplate.
The declarative workflow.
By moving dimension tracking into the template, you keep your component logic declarative. You avoid the need for onMount hooks to attach observers, which reduces the complexity of your script block.
a. Tracking dimensions with bind:clientWidth and bind:clientHeight
You can bind the dimensions of any block-level element to a variable. These bindings are read-only: Svelte updates the variable when the element changes size. The most common dimensions are clientWidth and clientHeight (which include padding but exclude borders/scrollbars) and offsetWidth and offsetHeight (which include borders/scrollbars).
<script>
let width;
</script>
<div bind:clientWidth={width} class="container">
The width of this container is {width}px
</div>
These bindings are powered by ResizeObserver under the hood. Whenever the container is resized—due to window changes, content injection, or CSS transitions—the width variable updates automatically, allowing you to recalculate layout properties or trigger internal component logic.
b. Tracking scroll position with bind:scrollY and bind:scrollX
Scrolling state is critical for UI effects like “sticky” headers or “back-to-top” buttons. By binding the window to scrollY or scrollX, you get a reactive variable representing the current scroll position. This is the most efficient way to track page scroll without manual listener management.
<script>
let y;
</script>
<svelte:window bind:scrollY={y} />
{#if y > 100}
<button>Back to Top</button>
{/if}
When you bind to the window using <svelte:window>, the variables y or x provide the current scroll offset. You can use these values in reactive declarations ($: ) to trigger side effects, such as adding a class to a header when the scroll position crosses a specific threshold.
c. Element-specific scroll bindings
You can also bind the scroll position of a specific container rather than the global window. This is used for custom scrollable areas, such as chat windows or sidebars. By binding scrollTop or scrollLeft to an element, you can both read the current position and write to it to force a scroll programmatically.
<script>
let div;
let scrollTop = 0;
</script>
<div bind:this={div} bind:scrollTop={scrollTop} class="scroll-box">
<!-- Content -->
</div>
<button on:click={() => scrollTop = 0}>Scroll to top</button>
This bidirectional binding is unique; unlike clientWidth (which is strictly read-only), bind:scrollTop allows you to set the value. Updating scrollTop will immediately jump the element’s scroll bar to that position, providing a clean API for controlling custom container scrolling.
Complete Example Session
// ============================================
// PART 1: MEASURING CONTAINER SIZE
// ============================================
<script>
let w;
</script>
<div bind:clientWidth={w}>Content</div>
<p>Width: {w}</p>
// ============================================
// PART 2: TRACKING PAGE SCROLL
// ============================================
<script>
let scrollY;
</script>
<svelte:window bind:scrollY />
<p>Position: {scrollY}</p>
// ============================================
// PART 3: CONTROLLED SCROLL
// ============================================
<script>
let container;
let top;
</script>
<div bind:scrollTop={top}>...</div>
<button on:click={() => top = 0}>Reset</button>
// ============================================
// PART 4: REACTIVE LOGIC
// ============================================
<script>
$: isFixed = scrollY > 50;
</script>
<nav class:fixed={isFixed}>Menu</nav>
These parts show the range of bindings: from reactive measurements of container widths to global and element-specific scroll control.
Quick Reference
Dimension Bindings (Read-only)
| Binding | Property Measured |
|---|---|
clientWidth | Content + Padding |
clientHeight | Content + Padding |
offsetWidth | Content + Padding + Border + Scrollbar |
offsetHeight | Content + Padding + Border + Scrollbar |
Scroll Bindings
| Binding | Target | Direction |
|---|---|---|
scrollY | <svelte:window> | Read-only |
scrollTop | <div> | Read / Write |
scrollLeft | <div> | Read / Write |
Best Practices
✅ Do This:
// Use bind for responsive logic
<div bind:clientWidth={w} /> // ✅
// Bind scroll to window for effects
<svelte:window bind:scrollY={y} /> // ✅
// Use scrollTop for manual scrolling
<div bind:scrollTop={top} /> // ✅
// Combine with reactive declarations
$: theme = w < 500 ? 'mobile' : 'desktop'; // ✅
❌ Don’t Do This:
// Avoid using window.scrollY manually
<svelte:window on:scroll={() => y = window.scrollY} /> // ❌
// Don't bind dimensions to non-block elements
<span></span> // ❌
// Don't perform heavy DOM reads in loop
element.getBoundingClientRect() // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
clientWidth is 0 | Hidden element | Check CSS display |
| Performance lag | Heavy reactive logic | Use $: with caution |
| SSR Issues | window is undefined | Use onMount or browser check |
| Inaccurate measure | Borders/Margin ignored | Use offsetWidth |
Real-World Examples
1. Sticky Header
<svelte:window bind:scrollY={y} />
<header class:scrolled={y > 50} />
2. Mobile Responsive Switcher
<div bind:clientWidth={w} />
{#if w < 600}<MobileNav />{/if}
3. Scroll to Bottom (Chat)
<div bind:scrollTop={top} />
<button on:click={() => top = 9999}>Go down</button>
4. Progress Bar
<div style="width: {scrollPercentage}%" />
5. Dynamic Grid Columns
<div bind:clientWidth={w} style="grid-cols: {w/200}" />
6. Infinite Scroll Trigger
<div bind:scrollY={y} />
{#if y + height > total} <LoadMore /> {/if}
7. Sidebar Auto-scroll
<div bind:scrollTop={val} />
8. Image Lazy Load
<div bind:clientHeight={h} />
9. Tooltip Positioning
<div bind:clientWidth={w} />
10. Header Parallax
<div style="top: {y * 0.5}px" />
Visual
Dimension Box Model
┌──────────────────────────────────────────────┐
│ ┌────────────────────────────────────────┐ │
│ │ PADDING + CONTENT = clientWidth │ │
│ └────────────────────────────────────────┘ │
│ │ │ │
│ └────────────────────────────────────────┘ │
│ offsetWidth (incl border) │
└──────────────────────────────────────────────┘
Scroll Position (Window)
┌──────────────────────────────────────────────┐
│ SCROLLABLE PAGE │
│ [header] │
│ [content] scrollY=0 --┐ │
│ [content] --┼─> bind:scrollY │
│ [content] scrollY=200 --┘ │
└──────────────────────────────────────────────┘
Bidirectional Scroll (Container)
┌──────────────────────────────────────────────┐
│ SCROLLABLE DIV │
│ ┌───────────────────────┐ │
│ │ bind:scrollTop │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ READ current pos │ │
│ │ WRITE to jump │ │
│ └───────────────────────┘ │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
clientWidth | Read-only |
clientHeight | Read-only |
scrollY | Read-only |
scrollTop | Read / Write |
bind:this | Required for manual ref |
| Performance | Optimized / Throttled |
Key takeaways:
- Bindings replace imperative measurement. They eliminate the need for
ResizeObserveroraddEventListenercode, handling updates reactively via Svelte’s engine. - Understand the box model. Choose
clientWidthfor content-focused math andoffsetWidthif your layout logic relies on visible borders and scrollbars. - Use
svelte:windowfor global scroll. It is the most performant way to track page scroll and trigger visual effects based on page depth. - Container scrolling is bidirectional.
scrollTopbindings allow both measuring how far a user has scrolled and forcing the scroll position to jump to a specific index. - Watch for SSR. Remember that
windowis not available on the server; ensure your scroll-tracking code is guarded or only runs in the browser.
Remember: Svelte dimension and scroll bindings are powerful tools that turn raw DOM layout data into reactive state variables. By keeping your layout logic declarative, these bindings allow for smooth, high-performance interactions like sticky headers, responsive design adjustments, and programmatic scroll control without the overhead of manual event management.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!