0
0
SASSmarkup~5 mins

Fluid spacing with calculations in SASS

Choose your learning style9 modes available
Introduction

Fluid spacing helps your website look good on all screen sizes by adjusting space smoothly. Calculations let you create these spaces easily and consistently.

You want margins or padding to grow or shrink between small phones and large desktops.
You want consistent spacing that changes smoothly instead of jumping at breakpoints.
You want to avoid writing many media queries for spacing.
You want to keep your design balanced on different screen widths.
You want to use math to create custom spacing scales.
Syntax
SASS
$space: calc(min + (max - min) * ((100vw - minViewport) / (maxViewport - minViewport)));

calc() lets you do math inside CSS or Sass.

Use vw units for viewport width to make spacing fluid.

Examples
This makes spacing start at 1rem on small screens (320px) and grow to 2rem on large screens (1280px).
SASS
$spacing: calc(1rem + (2rem - 1rem) * ((100vw - 320px) / (1280px - 320px)));
Padding fluidly changes from 0.5rem to 1.5rem between 400px and 1200px viewport widths.
SASS
$padding: calc(0.5rem + (1.5rem - 0.5rem) * ((100vw - 400px) / (1200px - 400px)));
Margin grows from 2rem to 4rem as screen width increases from 600px to 1600px.
SASS
$margin: calc(2rem + (4rem - 2rem) * ((100vw - 600px) / (1600px - 600px)));
Sample Program

This code creates a container with padding that grows fluidly from 1rem to 3rem as the screen width changes from 320px to 1280px. The background and border help you see the container's size change.

SASS
@use 'sass:math';

$min-space: 1rem;
$max-space: 3rem;
$min-vw: 320px;
$max-vw: 1280px;

$fluid-space: calc(#{$min-space} + (#{$max-space} - #{$min-space}) * ((100vw - #{$min-vw}) / (#{$max-vw} - #{$min-vw})));

.container {
  padding: $fluid-space;
  background-color: #e0f7fa;
  border: 1px solid #00796b;
  max-width: 800px;
  margin: 2rem auto;
  font-family: Arial, sans-serif;
}

.container p {
  margin: 0;
  font-size: 1rem;
  color: #004d40;
}
OutputSuccess
Important Notes

Remember to use calc() with interpolation #{} in Sass to combine variables and math.

Fluid spacing works best between two viewport widths; outside that range, spacing stays at min or max.

Test your design by resizing the browser to see the smooth spacing changes.

Summary

Fluid spacing adjusts space smoothly between screen sizes using calculations.

Use calc() with viewport units and Sass variables for easy control.

This technique reduces the need for many media queries and keeps designs balanced.