Command Palette

Search for a command to run...

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

Bars from divs and flexbox, with the awkward inputs

No library: a bar is a div, and its width is a percentage. The empty and all-zero cases are handled in share() and renderBars().

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?

Bars from divs and flexbox, with the awkward inputs

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

week:       74.6% 100% 94.2% 93.7% 91.4% 75.5% 86.4%
empty:      (no bars) | message: No rides to show.
one value:  100%
all equal:  100% 100%
all zero:   0% 0%