SASS: Defining linear sizes

Updated . Posted . Visible to the public.

Just dumping this in case somebody might need it.

When you need a CSS value (a padding, margin, height etc) to shrink/grow proportionally with the parent element, you normally use percentage values. However, if you need specific values at two given widths, you need to turn to linear functions Show archive.org snapshot . The mixin below gives you just that.

// Call with two desired values at two different widths.
// Returns a calc() expression that will scale proportionally between those two.
// Example:
//   Spacing should be 15px at 320px parent container width, and 80px at 1150px
//   parent container width. => linear-scale(320, 15, 1150, 80)
@function linear-scale($width1, $spacing1, $width2, $spacing2)
  //
    Linear equations:
    $width1 * $relative + $static = $spacing1
    $width2 * $relative + $static = $spacing2

  $relative: ($spacing2 - $spacing1) / ($width2 - $width1)
  $static: $spacing1 - ($width1 * $relative)

  @return calc(#{$relative * 100%} + #{$static * 1px})
Dominik Schöler
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2017-03-17 16:41)