Get Dimensions of Element in Svelte
- 1 minute read
Svelte offers some built-in
dimension bindings, including clientWidth
and clientHeight
, which bind a dimension of an attached element to a variable.
Here is an example, which attaches the width and height (in pixels) of a paragraph element:
<script>
let width;
let height;
</script>
Paragraph width: {width}px
Paragraph height: {height}px
<p bind:clientWidth={width} bind:clientHeight={height}>
This is some example text.
</p>
You cannot modify the dimensions of an element by mutating clientWidth
or clientHeight
, because they are read-only attributes.
Furthermore, you should be careful with how many components you watch the dimensions of, because they calculate the dimensions in a rather performance-intensive way.
Conclusion
And that is how you subscribe to the dimensions of a given HTML element in Svelte!