Every block-level element has clientWidth
, clientHeight
, offsetWidth
and offsetHeight
bindings:
App.svelte
<div bind:clientWidth={w} bind:clientHeight={h}>
<span style="font-size: {size}px" contenteditable>{text}</span>
<span class="size">{w} x {h}px</span>
</div>
These bindings are readonly — changing the values of w
and h
won't have any effect on the element.
Elements are measured using a technique similar to this one. There is some overhead involved, so it's not recommended to use this for large numbers of elements.
display: inline
elements cannot be measured with this approach; nor can elements that can't contain other elements (such as<canvas>
). In these cases you will need to measure a wrapper element instead.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<script>
let w;
let h;
let size = 42;
let text = 'edit this text';
</script>
<label>
<input type="range" bind:value={size} min="10" max="100" />
font size ({size}px)
</label>
<div>
<span style="font-size: {size}px" contenteditable>{text}</span>
<span class="size">{w} x {h}px</span>
</div>
<style>
div {
position: relative;
display: inline-block;
padding: 0.5rem;
background: hsla(15, 100%, 50%, 0.1);
border: 1px solid hsl(15, 100%, 50%);
}
.size {
position: absolute;
right: -1px;
bottom: -1.4em;
line-height: 1;
background: hsl(15, 100%, 50%);
color: white;
padding: 0.2em 0.5em;
white-space: pre;
}
</style>