Skip to content

Instantly share code, notes, and snippets.

@bytrangle
Last active January 12, 2021 07:36
Show Gist options
  • Save bytrangle/788875bac3be2532ed1a19e9b06b6271 to your computer and use it in GitHub Desktop.
Save bytrangle/788875bac3be2532ed1a19e9b06b6271 to your computer and use it in GitHub Desktop.
Create a coherent spacing system using Sass and CSS variable
:root {
--spacing__base_unit: 16px;
--spacing__unit--0_25: calc(var(--spacing__base_unit) * 0.25) ;
--spacing__unit--0_5: calc(var(--spacing__base_unit) * 0.5) ;
--spacing__unit--0_75: calc(var(--spacing__base_unit) * 0.75) ;
--spacing__unit--1: calc(var(--spacing__base_unit) * 1) ;
--spacing__unit--1_5: calc(var(--spacing__base_unit) * 1.5) ;
--spacing__unit--2: calc(var(--spacing__base_unit) * 2) ;
--spacing__unit--3: calc(var(--spacing__base_unit) * 3) ;
--spacing__unit--4: calc(var(--spacing__base_unit) * 4) ;
--spacing__unit--6: calc(var(--spacing__base_unit) * 6) ;
--spacing__unit--8: calc(var(--spacing__base_unit) * 8) ;
--spacing__unit--12: calc(var(--spacing__base_unit) * 12) ;
--spacing__unit--16: calc(var(--spacing__base_unit) * 16) ;
--spacing__unit--24: calc(var(--spacing__base_unit) * 24) ;
--spacing__unit--32: calc(var(--spacing__base_unit) * 32) ;
--spacing__unit--40: calc(var(--spacing__base_unit) * 40) ;
--spacing__unit--48: calc(var(--spacing__base_unit) * 48) ;
}
{
"sass": {
"compiler": "dart-sass/1.26.11",
"extensions": {},
"syntax": "SCSS",
"outputStyle": "expanded"
},
"autoprefixer": false
}
// Helper function to replace dot with underscore because we can't have dot in CSS variables.
@function replaceString($string, $target, $replace: '_') {
// Find index of the character to be replaced
$index: str-index($string, $target);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-slice($string, $index + 1);
}
// If the target character is not part of the string, just return the whole string
@else {
@return $string;
}
}
// 16px is a great number to start as a base unit, because it's an even number that divdes nicely by 4, and it also happens to be the default font size in every major web browser.
$base-unit: 16px;
$base-unit-variable: '--spacing__base_unit';
// The values at the small end of the scale start packed together, and get progressively more spaced apart as you get higher up the scale.
$scaleSystem: 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32, 40, 48;
:root {
#{$base-unit-variable}: $base-unit;
@each $scale in $scaleSystem {
--spacing__unit--#{replaceString(#{$scale}, '.')}: calc(var(#{$base-unit-variable}) * #{$scale})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment