Skip to content

Instantly share code, notes, and snippets.

@robpataki
Created November 18, 2020 15:50
Show Gist options
  • Save robpataki/b5dec117cb360c51212d8dd81ce2ac7a to your computer and use it in GitHub Desktop.
Save robpataki/b5dec117cb360c51212d8dd81ce2ac7a to your computer and use it in GitHub Desktop.
SASS Metaprogramming example - generate utility classes and placeholders
// stylelint-disable declaration-no-important
@use "sass:string";
// Settings
@use "scss-core/settings/vars";
// Use the built-in generator below to generate simple utility class and placeholder pairs
//
// An example utility:
// Placeholder for internal use:
// %u-no-padding {
// padding: 0;
// }
//
// "Forceful" utility class for inline use:
// .u-no-padding {
// padding: 0 !important;
// }
$-utils: (
// Spacing
"no-gutters": (
"padding-right": 0,
"padding-left": 0,
),
"no-padding": (
"padding": 0
),
"no-margin": (
"margin": 0
),
// Text alignment
"text-right": (
"text-align": right
),
"text-left": (
"text-align": left
),
"text-centre": (
"text-align": center
),
// Font family
"ff": (
"font-family": vars.$font-family
),
"ff-mono": (
"font-family": vars.$font-family-mono
),
// Font weight
"fw-regular": (
"font-weight": 400
),
"fw-light": (
"font-weight": 200
),
"fw-bold": (
"font-weight": 600
)
);
// Generate both util classes and placeholders - util classes with !important
@each $name, $props in $-utils {
$prefixes: ".", "%", "mixin";
@each $prefix in $prefixes {
#{$prefix}#{"u-"}#{$name} {
@each $-key, $-value in $props {
#{$-key}: $-value if($prefix == ".", !important, null);
}
}
}
}
// Add more complex utilities below...
%u-box-sizing,
.u-box-sizing {
&,
&:before,
&:after {
box-sizing: border-box;
}
}
%u-sr-only,
.u-sr-only {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
// Backgrounds and colours
@each $colourKey, $colourValue in vars.$colours {
.u-c-#{$colourKey} {
color: $colourValue !important;
}
.u-bg-#{$colourKey} {
background-color: $colourValue !important;
}
}
// stylelint-enable declaration-no-important
@mixin no-gutters () {
padding-right: 0;
padding-left: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment