The innerWidth property reports the browser window’s viewport width in CSS pixels. Responsive visualizations use it to choose layouts, size text, and calculate SVG dimensions. section 9.2.1 section 14.4.1
Read it through window.innerWidth, usually by wrapping the access in a helper such as getWindowWidth(). Store the result, then recalculate dependent values when the window emits a resize event. section 9.2.1 section 10.2.1
Use the reported width to drive visible responsive behavior:
- Map width to font size with a clamped D3 linear scale, keeping labels readable across desktop and phone layouts. section 9.2.1 section 10.2.1
- Select desktop or mobile layouts at a breakpoint, and switch rendered components when the width crosses that breakpoint. section 9.3.2
- Calculate SVG width, grid columns, rows, and height from the current width in a reactive Svelte component. section 14.4.1
Resize-driven chart update
A chart can initialize windowWidth from getWindowWidth(), apply fontSizeScale(windowWidth) to text, and repeat that update inside a window resize listener. Centralizing the update in resizeChart() lets page load and resizing share one implementation. section 9.2.1
const resizeChart = () => {
d3.selectAll("#line-chart text") #1
.style("font-size", `${fontSizeScale(
windowWidth)}px`);
};
window.addEventListener("resize", () => { #2
windowWidth = getWindowWidth();
resizeChart();
});
Inspect the complete resize pattern: read windowWidth, update chart text, and register the resize event listener. section 9.2.1
Listing 14.2 Dynamically updating the width (Grid.svelte)
<script>
let windowWidth;
const gridContainer = 1400;
const padding = 30;
let svgWidth;
$: switch (true) { #1
case windowWidth >= gridContainer:
svgWidth = (10 / 12) * (gridContainer -
2 * padding);
break;
case windowWidth < gridContainer &&
windowWidth >= 768:
svgWidth = (10 / 12) * (windowWidth -
2 * padding);
break;
default:
svgWidth = windowWidth - 2 * padding;
}
</script>
<svelte:window bind:innerWidth={windowWidth} /> #2
<svg width={svgWidth} /> #3
<style>
svg {
border: 1px solid magenta;
}
</style>
Compare Svelte’s reactive alternative, which binds windowWidth directly to innerWidth and derives the SVG width from it. section 14.4.1
