0
0
SASSmarkup~5 mins

Number types and units in SASS

Choose your learning style9 modes available
Introduction

Numbers in Sass help you control sizes, spaces, and colors. Units tell the browser what those numbers mean, like pixels or percentages.

Setting the width or height of a box in pixels or percentages.
Defining font sizes using rem or em units for better scaling.
Creating spacing like margins and padding with units.
Adjusting colors with numbers for opacity or lightness.
Using calculations to combine different units for responsive design.
Syntax
SASS
$variable: 10px;
$percentage: 50%;
$number: 1.5;
$em-size: 2em;

Numbers can have units like px, %, em, rem, vh, vw, etc.

Unitless numbers are just plain numbers without any unit.

Examples
This sets a width of 100 pixels.
SASS
$width: 100px;
This is a unitless number, often used for opacity or ratios.
SASS
$opacity: 0.5;
This sets font size relative to the root font size.
SASS
$font-size: 1.2rem;
This sets margin as a percentage of the parent element.
SASS
$margin: 10%;
Sample Program

This Sass code sets base font size and scales the heading size using numbers and units. It uses rem for spacing and pixels for font size calculation.

SASS
@use 'sass:math';

$base-font-size: 16px;
$scale-factor: 1.25;

body {
  font-size: $base-font-size;
  margin: 2rem;
}

h1 {
  font-size: math.round($base-font-size * $scale-factor * 10) / 10;
  margin-bottom: 1.5rem;
}

p {
  font-size: 1rem;
  line-height: 1.5;
  margin-bottom: 1rem;
}
OutputSuccess
Important Notes

Always use units when needed to avoid errors in calculations.

You can do math with numbers and units in Sass, but units must be compatible.

Use unitless numbers for things like opacity or z-index where units don't apply.

Summary

Numbers in Sass can have units like px, %, em, rem, or be unitless.

Units tell the browser how to interpret the number.

Use numbers and units to control sizes, spacing, and other styles precisely.