0
0
SASSmarkup~5 mins

Spacing utility generation in SASS

Choose your learning style9 modes available
Introduction

Spacing utilities help you add consistent space around elements quickly. They save time and keep your design neat.

When you want to add margin or padding without writing custom CSS each time.
When you need consistent spacing between buttons, text, or images.
When building a responsive layout that adjusts spacing easily.
When you want to keep your CSS small and reusable.
When working with a team to keep spacing rules consistent.
Syntax
SASS
@mixin spacing($property, $size) {
  #{$property}: $size;
}

// Usage example:
@include spacing(margin, 1rem);

The @mixin defines reusable code blocks in Sass.

You can pass the CSS property and size as variables to create flexible spacing utilities.

Examples
This adds padding: 2rem; to the element.
SASS
@mixin spacing($property, $size) {
  #{$property}: $size;
}

@include spacing(padding, 2rem);
This adds margin-top: 1.5rem; to the element.
SASS
@mixin spacing($property, $size) {
  #{$property}: $size;
}

@include spacing(margin-top, 1.5rem);
This uses a map of sizes to apply margin: 1rem; by referring to the size name.
SASS
$spacings: (small: 0.5rem, medium: 1rem, large: 2rem);

@mixin spacing($property, $size-name) {
  #{$property}: map-get($spacings, $size-name);
}

@include spacing(margin, medium);
Sample Program

This Sass code creates a spacing map with named sizes. The spacing mixin applies margin or padding using these sizes. The container has medium margin and small padding. The button has large top margin and extra small padding.

SASS
@use 'sass:map';

$spacings: (
  none: 0,
  xs: 0.25rem,
  sm: 0.5rem,
  md: 1rem,
  lg: 2rem,
  xl: 4rem
);

@mixin spacing($property, $size-name) {
  $size: map.get($spacings, $size-name);
  #{$property}: $size;
}

.container {
  @include spacing(margin, md);
  @include spacing(padding, sm);
  background-color: #f0f0f0;
  border: 1px solid #ccc;
}

.button {
  @include spacing(margin-top, lg);
  @include spacing(padding, xs);
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 0.25rem;
  cursor: pointer;
}
OutputSuccess
Important Notes

Use named sizes to keep spacing consistent across your site.

You can extend this mixin to handle multiple properties or directions (top, bottom, left, right).

Remember to compile your Sass to CSS before using it in the browser.

Summary

Spacing utilities help add margin and padding quickly and consistently.

Sass mixins let you reuse spacing code with different sizes and properties.

Using a map of sizes keeps your design system organized and easy to update.