A look at mixins and functions in SCSS. Reusable chunks of CSS and calculated values you can use across your stylesheets.
Mixins
Mixins let you define a block of CSS once and include it in multiple selectors. They are handy for repetitive styles, vendor-prefix patterns, and anything you would otherwise copy and paste.
Creating and using a mixin
Create a mixin with the @mixin directive:
@mixin center-content {
display: flex;
justify-content: center;
align-items: center;
}
Include it in a selector with @include:
.container {
@include center-content;
}
This inserts the styles from center-content into .container.
Mixins with arguments
Mixins can take parameters, which makes them more flexible:
A text shadow mixin:
@mixin text-shadow($x-offset, $y-offset, $blur, $color) {
text-shadow: $x-offset $y-offset $blur $color;
}
.button {
@include text-shadow(1px, 1px, 2px, rgba(0, 0, 0, 0.5));
}
Each call can pass different offset, blur, and colour values.
Functions
Functions take inputs, do a calculation, and return a value. Use them when you need to generate a value rather than output a block of CSS.
Writing a simple function
@function calculate-rem($size, $base: 16px) {
@return $size / $base * 1rem;
}
body {
font-size: calculate-rem(18px);
}
This converts pixel values to rem – useful for responsive sizing.
Combining mixins and functions
Functions calculate values; mixins apply styles. They work well together.
A practical example
Say you need buttons in different sizes. A function calculates padding; a mixin applies the sizing:
@function calculate-padding($size) {
@return $size / 2;
}
@mixin button-size($font-size) {
font-size: $font-size;
padding: calculate-padding($font-size) 1rem;
}
.button-small {
@include button-size(12px);
}
.button-large {
@include button-size(18px);
}
Change the sizing logic in one place and both button classes update. That is the DRY (Don’t Repeat Yourself) principle in action.
Best practices for mixins and functions
- Descriptive names: name mixins and functions clearly so their purpose is obvious.
- Avoid overuse: not everything needs a mixin. Simple one-off styles are fine as plain CSS.
- Documentation: comment non-obvious mixins and functions, especially in shared projects.
Mixins and functions in responsive design
Mixins are particularly useful for media queries. You can define breakpoints once and reuse them:
@mixin respond-to($media) {
@if $media == 'phone' {
@media (max-width: 600px) { @content; }
} @else if $media == 'tablet' {
@media (max-width: 900px) { @content; }
}
}
.container {
@include respond-to('phone') {
padding: calculate-rem(10px);
}
}
This keeps media query breakpoints consistent across the project.
Mixins and functions are two of the most practical SCSS features. Start with a few simple ones and build up as your project needs them.

