Skip to content

Instantly share code, notes, and snippets.

@olets
Last active August 2, 2018 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olets/6cdc20da050303dcb712c9a8f1d842b6 to your computer and use it in GitHub Desktop.
Save olets/6cdc20da050303dcb712c9a8f1d842b6 to your computer and use it in GitHub Desktop.
Sass styles for responsive sizing and spacing
// ----
// Sass (v3.4.25)
// Compass (v1.0.3)
// ----
// VARIABLES
$widths: (
// devices
tablet-to-mobile: 768px//,
// other breakpoints
// design-related
// full, wide, narrow, etc.
);
$queries: (
mobile: '(max-width: #{map-get($widths,"tablet-to-mobile")})'//,
// repeat for e.g. desktop, tablet, tablet-up, tablet-down, full-down
);
$unit: 10px;
$mobile-unit: 6px;
$spaces: (
loose: 5,
medium: 4
);
// MIXINS & FUNCTIONS
@mixin media($query) {
@media #{map-get($queries, $query)} {
@content
}
}
@function unit-relative($multiple: 1) {
@return calc(#{$multiple} * var(--responsive-unit));
}
@function unit-absolute($multiple: 1) {
$static-size: $multiple * $unit;
@return $static-size;
}
// STYLES
:root {
--responsive-unit: #{$unit};
@include media(tablet-down) {
--responsive-unit: #{$mobile-unit};
}
}
%spacing-relative- {
@each $spacing-name, $spacing-size in $spaces {
&#{$spacing-name} {
margin-bottom: unit-relative($spacing-size);
margin-top: unit-relative($spacing-size);
}
}
}
%spacing-absolute- {
@each $spacing-name, $spacing-size in $spaces {
&#{$spacing-name} {
margin-bottom: unit-absolute($spacing-size);
margin-top: unit-absolute($spacing-size);
}
}
}
.example--unit-relative {
padding-left: unit-relative(2);
width: unit-relative(4);
}
.example--unit-absolute {
padding-left: unit-static(2);
}
.example--spacing-relative {
@extend %spacing-relative-loose;
}
.example--spacing-absolute {
@extend %spacing-absolute-loose;
}
:root {
--responsive-unit: 10px;
}
@media (max-width: 1024px) {
:root {
--responsive-unit: 6px;
}
}
.example--spacing-relative {
margin-bottom: calc(5 * var(--responsive-unit));
margin-top: calc(5 * var(--responsive-unit));
}
.example--spacing-absolute {
margin-bottom: 50px;
margin-top: 50px;
}
.example--unit-relative {
padding-left: calc(2 * var(--responsive-unit));
width: calc(4 * var(--responsive-unit));
}
.example--unit-absolute {
padding-left: unit-static(2);
}
@olets
Copy link
Author

olets commented Aug 2, 2018

SassMeister: https://www.sassmeister.com/gist/6cdc20da050303dcb712c9a8f1d842b6

Codepen: https://codepen.io/henry/pen/ejrjVE

Remember you can't use unit-relative inside a calc(). If you need to do something like calc(unit($someVal) * $someOtherVal), just do

$myVal: $someVal * $someOtherVal;
…calc(unit-relative($myVal))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment