The starting point was marvelapp/devices.css, a library that renders hardware such as the iPhone X in pure CSS rather than as an image, which makes an interactive application demo inside the mock phone possible. Its weakness: every device uses fixed pixel sizing, so nothing can be scaled, and the open issue tracking the problem lists options that either break in some browsers or carry other drawbacks. Making those devices resizable means touching every pixel measurement in a multi-thousand-line Sass file.

The three CSS mechanisms behind the resize

The rewrite rests on calc(), a CSS custom property named --size-divisor read through var(), and @media queries keyed on min-width.

Arithmetic inside length values

calc() evaluates an expression and returns the result with appropriate units, including expressions whose inputs mix units. Halving a device means dividing each pixel measurement by two.

Before:

width: 375px;

After:

width: calc(375px / 2);

The result is half the length. For the whole device to scale, every pixel value in the library has to be wrapped this way.

A single divisor for the entire stylesheet

A CSS variable is declared at the top of the file before any use.

:root {
  --size-divisor: 3;
}

From there, var() exposes the value everywhere. Resizing a device then divides all pixel counts by the same number, which avoids magic numbers scattered through the code.

width: calc(375px / var(--size-divisor));

With the declaration above, this yields the original width divided by three, in pixels.

Breakpoints for screen width

Responsiveness comes from media queries that watch screen width and fire when it crosses chosen thresholds. The breakpoints follow Bootstrap's xs, sm and larger sizes. No breakpoint is needed at a minimum width of zero — the :root declaration at the top of the file covers extra-small screens. The queries belong at the end of the document, ordered by ascending min-width.

@media (min-width: 576px) {
  :root {
    --size-divisor: 2;
  }
}
@media (min-width: 768px) {
  :root {
    --size-divisor: 1.5;
  }
}
@media (min-width: 992px) { 
  :root {
    --size-divisor: 1;
  }
}
@media (min-width: 1200px) { 
  :root {
    --size-divisor: .67;
  }
}

Adjusting the values in these queries changes how much the device resizes. calc() handles floats as readily as integers.

Generating the new library with Python

The target output is a file that opens with the variable declaration, contains the full library with every pixel measurement wrapped in calc(), and closes with the media queries. Hand-editing thousands of lines is impractical, so a Python script performs the conversion.

def scale(token):
  if token[-2:] == ';\n':
    return 'calc(' + token[:-2] + ' / var(--size-divisor));\n'
  elif token[-3:] == ');\n':
    return '(' + token[:-3] + ' / var(--size-divisor));\n'
  return 'calc(' + token + ' / var(--size-divisor))'

Given a string containing NNpx, the function returns calc(NNpx / var(--size-divisor));. The file contains only three pixel patterns — NNpx, NNpx; and NNpx); — and the rest is string concatenation. The tokens have already been produced by splitting each line on space characters.

def build_file(scss):
  out = ':root {\n\t--size-divisor: 3;\n}\n\n'
  for line in scss:
    tokens = line.split(' ')
    for i in range(len(tokens)):
      if 'px' in tokens[i]:
        tokens[i] = scale(tokens[i])
    out += ' '.join(tokens)
  out += "@media (min-width: 576px) {\n  \
    :root {\n\t--size-divisor: 2;\n  \
    }\n}\n\n@media (min-width: 768px) {\n \
    :root {\n\t--size-divisor: 1.5;\n  \
    }\n}\n\n@media (min-width: 992px) { \
    \n  :root {\n\t--size-divisor: 1;\n  \
    }\n}\n\n@media (min-width: 1200px) { \
    \n  :root {\n\t--size-divisor: .67;\n  }\n}"
  return out

This builder declares the CSS variable, walks the old library looking for pixel measurements, scales each of the hundreds of matching tokens, and rejoins the tokens so the original line structure survives. It then appends the media queries and returns the library as a string. A short driver reads and writes the files.

if __name__ == '__main__':
  f = open('devices_old.scss', 'r')
  scss = f.readlines()
  f.close()
  out = build_file(scss)
  f = open('devices_new.scss', 'w')
  f.write(out)
  f.close()

The result is a new Sass library; the CSS file for final use is produced with:

sass devices_new.scss devices.css

The rewritten library ships the same devices, now responsive. The output file runs to thousands of lines and is published on GitHub.

Alternatives considered and why they fell short

zoom

Scaling with zoom would resize the device uniformly, pair with media queries as the chosen solution does, and need neither calc() nor a custom property. But zoom is non-standard and is not supported in Firefox, among other limitations.

Swapping px for em

Replacing every px with em ties device size to font size. Fitting a device on a mobile display can then demand minuscule font sizes below the minimums browsers such as Chrome enforce, and visitors using assistive technology that increases font size introduce further trouble. Scaling all values down by a factor of 100 and applying standard font sizes would address that, but needs just as much preprocessing, and performing the calculations directly is cleaner than manipulating font sizes.

scale()

The scale() function returns a <transform-function> for a style's transform attribute and can resize entire objects; Chris Coyier prepared an example using it. It is a strong approach, but it leaves the actual CSS measurements of the device unchanged, which matters when complex UI elements are rendered on the device's “screen.”

Trade-offs and maintenance

Hundreds of calc() calls are not the first tool one would reach for when writing such a library from scratch, but for making an existing fixed-size library resizable the method works. Variables plus media queries supply the responsive behavior, and if the underlying library is updated, the Python script can process the changes into a new version of the responsive build.