Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 1.4 — viewBox and preserveAspectRatio
Data Visualization · Example 2 of 3

Meet, slice and none in a wide box

A square drawing in a 3-to-1 box. Meet fits it whole, slice crops it, none distorts it. The last two lines show where the nine alignments place it.

The viewBox attribute gives an SVG its own coordinate window, so the drawing scales to whatever size the screen gives it. preserveAspectRatio decides what happens when window and screen have different shapes: fit, fill, or stretch.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

A drawing is 380 wide and 210 tall (as in the Phase 0 week chart). Write the opening <svg> tag so it fills its container's width and keeps the right shape.

02

You want to zoom into the area from x = 100 to x = 200 and y = 20 to y = 70 of a drawing. What viewBox do you write, and what is the scale if the SVG is 400 pixels wide?

Explain it without notes

01

What do the four numbers of a viewBox mean, and how does the browser use them?

02

What is the difference between meet and slice?

03

Why does an SVG with width="100%" and no viewBox stay 150 pixels tall?

04

What do you see when a viewBox is 0 0 0 100, 0 0 -200 100 and 0 0 NaN 100?

Meet, slice and none in a wide box

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

meet (the default): scale 1.0 across, 1.0 down, offset 100, 0
slice, centred: scale 3.0 across, 3.0 down, offset 0, -100
none, stretched: scale 3.0 across, 1.0 down, offset 0, 0
wide box, xMin / xMid / xMax (YMid): 0,0   100,0   200,0
tall box, YMin / YMid / YMax (xMid): 0,0   0,100   0,200