Command Palette

Search for a command to run...

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

Responsive width, and viewBoxes that are wrong

With a viewBox the height follows the width. The zero-width viewBox draws nothing (look at the blank box in the preview); the negative and three-number ones print their errors and show scale 1 because the browser ignored them.

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?

Responsive width, and viewBoxes that are wrong

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

viewBox 0 0 200 100 in a 160px box: SVG is 160 x 80, scale 0.8
viewBox 0 0 200 100 in a 240px box: SVG is 240 x 120, scale 1.2
viewBox 0 0 200 100 in a 320px box: SVG is 320 x 160, scale 1.6
no viewBox          in a 240px box: SVG is 240 x 150, scale 1
zero width (blank)   in a 240px box: SVG is 240 x 150, scale 1
negative width       in a 240px box: SVG is 240 x 150, scale 1
Error: <svg> attribute viewBox: A negative value is not valid. ("0 0 -200 100")
three numbers only   in a 240px box: SVG is 240 x 150, scale 1
Error: <svg> attribute viewBox: Unexpected end of attribute. Expected number, "0 0 200".
NaN                  in a 240px box: SVG is 240 x 150, scale 1
Error: <svg> attribute viewBox: Expected number, "0 0 NaN 100".