Every block-level element has clientWidth
, clientHeight
, offsetWidth
and offsetHeight
bindings:
<div bind:clientWidth={w} bind:clientHeight={h}>
<span style="font-size: {size}px">{text}</span>
</div>
These bindings are readonly — changing the values of w
and h
won't have any effect.
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.
App.svelte
xxxxxxxxxx
21
1
<script>
2
let w;
3
let h;
4
let size = 42;
5
let text = 'edit me';
6
</script>
7
8
<style>
9
input { display: block; }
10
div { display: inline-block; }
11
span { word-break: break-all; }
12
</style>
13
14
<input type=range bind:value={size}>
15
<input bind:value={text}>
16
17
<p>size: {w}px x {h}px</p>
18
19
<div>
20
<span style="font-size: {size}px">{text}</span>
Console
xxxxxxxxxx
134
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
attr,
6
detach,
7
element,
8
init,
9
insert,
10
listen,
11
noop,
12
run_all,
13
safe_not_equal,
14
set_data,
15
set_input_value,
16
set_style,
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
input.svelte-mc7rq7{display:block}div.svelte-mc7rq7{display:inline-block}span.svelte-mc7rq7{word-break:break-all}