Purrx

Padding, gap and splitting space

The two functions at the heart of a flexbox-style layout engine: take padding off a box, and share space between fixed-size and growing children with gaps.

12 min+30 XPHands-on

A sounds big, but it's mostly two questions asked over and over. How much room is left inside this box? And how do I share that room between its children?

Boxes

Every area on a slide is a box: { x, y, w, h } in points, with x, y the top-left corner. The whole slide is { x: 0, y: 0, w: 720, h: 405 }.

padding

child 1

gap

child 2

gap

child 3
Padding is space inside the container's edge. Gap is space between children, and only between them. There is deliberately no margin: two ways to add the same space is how layouts double up.

innerBox: taking padding off

Padding moves the top-left corner in, and makes the box narrower and shorter by the padding on both sides. With 48 points of padding, a 720-wide slide leaves 624 points for its children. If the padding is bigger than the box, the result is zero, never negative: negative widths turn into strange bugs three steps later.

splitSpace: sharing along one direction

A container gives each child some share of its width (in a row) or height (in a column). Each child asks in one of two ways:

  • { size: 100 }: exactly 100 points.
  • { grow: 1 }: a share of what's left. A child with grow: 2 gets twice as much as one with grow: 1.
size 100
gap 20
grow 1 → 80
gap 20
grow 1 → 80

total 300 points

splitSpace(300, [{ size: 100 }, { grow: 1 }, { grow: 1 }], 20): gaps come off first (40), fixed sizes next (100), and the grow items share the remaining 160.
the order matters
splitSpace(300, [{ size: 100 }, { grow: 1 }, { grow: 1 }], 20)

1. gaps first:     3 items → 2 gaps × 20 = 40      available = 260
2. fixed sizes:    100                              leftover  = 160
3. grow shares:    160 × 1/2 = 80, 160 × 1/2 = 80
                                                    → [100, 80, 80]

Key takeaways

  • Padding shrinks the box children can use; gaps come off before anything is shared out.
  • Fixed sizes are served first, and grow items share whatever is left in proportion.
  • When fixed sizes don't fit, squeeze them all by the same factor so nothing leaves the slide.

Sign in to run the exercise

Reading is free. Writing code here needs an account so we have somewhere to keep your Gemini key and the +30 XP you are about to earn.