Exercise 1 solution: a scale-to-CSS generator ============================================= """Generate CSS custom properties for a modular scale. py scale_css.py 16 1.25 """ import sys ROLES = [(-1, "caption"), (0, "body"), (1, "lead"), (2, "h3"), (3, "h2"), (4, "h1")] def build(base_px, ratio): lines = [":root {"] for step, role in ROLES: px = base_px * ratio ** step lines.append(f" --size-{role}: {px / 16:.3f}rem; /* {px:.1f}px at the default root */") lines.append("}") return "\n".join(lines) def check(base_px, ratio): sizes = [base_px * ratio ** s for s, _ in ROLES] notes = [] if sizes[0] < 12: notes.append(f"caption is only {sizes[0]:.1f}px: too small to read comfortably") if sizes[-1] > 64: notes.append(f"h1 is {sizes[-1]:.1f}px: too big for most pages, try a smaller ratio") return notes if __name__ == "__main__": base = float(sys.argv[1]) if len(sys.argv) > 1 else 16 ratio = float(sys.argv[2]) if len(sys.argv) > 2 else 1.25 print(build(base, ratio)) for note in check(base, ratio): print("WARNING:", note) Output of: py scale_css.py 16 1.25 ----------------------------------- :root { --size-caption: 0.800rem; /* 12.8px at the default root */ --size-body: 1.000rem; /* 16.0px at the default root */ --size-lead: 1.250rem; /* 20.0px at the default root */ --size-h3: 1.562rem; /* 25.0px at the default root */ --size-h2: 1.953rem; /* 31.2px at the default root */ --size-h1: 2.441rem; /* 39.1px at the default root */ } Output of: py scale_css.py 16 1.618 ----------------------------------- :root { --size-caption: 0.618rem; /* 9.9px at the default root */ --size-body: 1.000rem; /* 16.0px at the default root */ --size-lead: 1.618rem; /* 25.9px at the default root */ --size-h3: 2.618rem; /* 41.9px at the default root */ --size-h2: 4.236rem; /* 67.8px at the default root */ --size-h1: 6.854rem; /* 109.7px at the default root */ } WARNING: caption is only 9.9px: too small to read comfortably WARNING: h1 is 109.7px: too big for most pages, try a smaller ratio What to take from it -------------------- * A scale is just base x ratio ** step. Negative steps go below the body size (captions), positive steps go above it (headings). * The same code with a bigger ratio gives wildly different pages: the golden ratio is far too steep for a text-heavy page, which is why the script warns. * Dividing by 16 turns px into rem, so every size still follows the reader's browser setting. * A sensible next step is to add a check that the caption never drops below about 12px (check) and to let the script print the CSS to a file.