Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.1 — Bars with HTML and CSS
Data Visualization · Example 2 of 2

When a bar has no honest width: a silent failure, and a sparkline

A failure that prints no error: three of the bars are full length although their numbers are zero-by-zero, negative and missing.

A bar chart can be a stack of coloured boxes whose width comes from a number. HTML and CSS draw it with tools you already know, and it is often all a small chart needs. It also teaches the first rule of every chart: turn a number into a size.

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

Add a "how it looks with 25 stations" case: render 25 rows (value i * 100, label Station i) and say what happens to the page. What would you do about it?

02

Write shareLabel(value, most) that returns the string "74.6%" for a normal bar, "no data" when the value is null or undefined, and "0%" for 0. Show three calls.

Explain it without notes

01

How is the width of each bar worked out in the first example, and why is Tuesday exactly 100%?

02

Why does a bar for a negative number, a missing number or 0 ÷ 0 come out full length, and how do you prevent it?

03

Why use a percentage width for a bar inside a track, rather than a pixel width?

04

When would you choose HTML and CSS bars over an SVG chart, and when not?

When a bar has no honest width: a silent failure, and a sparkline

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

normal     style.width = "50%" -> drawn 100 px of 200
zero value style.width = "0%" -> drawn 0 px of 200
all zero   style.width = "" -> drawn 200 px of 200
negative   style.width = "" -> drawn 200 px of 200
missing    style.width = "" -> drawn 200 px of 200
long label style.width = "40%" -> drawn 80 px of 200
Sparkline heights: 12px 16px 15px 15px 15px 12px 14px