Spacing utilities help you add consistent space around elements quickly. They save time and keep your design neat.
Spacing utility generation in 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.
padding: 2rem; to the element.@mixin spacing($property, $size) { #{$property}: $size; } @include spacing(padding, 2rem);
margin-top: 1.5rem; to the element.@mixin spacing($property, $size) { #{$property}: $size; } @include spacing(margin-top, 1.5rem);
margin: 1rem; by referring to the size name.$spacings: (small: 0.5rem, medium: 1rem, large: 2rem); @mixin spacing($property, $size-name) { #{$property}: map-get($spacings, $size-name); } @include spacing(margin, medium);
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.
@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; }
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.
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.