Parent-Scoped mixins Sass

I recently had a need to build a Sass mixin that didn’t produce its output inside of its heirarchy. It’s easy, but wasn’t obvious in the documentation:

Typically I do my mixins like this:

@mixin scale($val) {
	-webkit-transform: scale($val);
	-moz-transform: scale($val);
	-ms-transform: scale($val);
	-o-transform: scale($val);
	transform: scale($val);
.btn {
	@include scale(0.5);

Which, when you use it produces output like this:

.btn {
	-webkit-transform: scale(0.5);
	-moz-transform: scale(0.5);
	-ms-transform: scale(0.5);
	-o-transform: scale(0.5);
	transform: scale(0.5);

My need was a page-wide change. If the body tag had a specific selector, I needed particular children to have different styles. Here’s how it’s done:

@mixin foreign-button($val) {
	body.russian & {
	background-image: url('russian/'+$val);
	body.spanish & {
		background-image: url('spanish/'+$val);
.btn {
	@include foreign-button('path/to/image.png');

The output of this method looks like this:

body.russian .btn {
	background-image: url('russian/path/to/image.png');
body.spanish .btn {
	background-image: url('spanish/path/to/image.png');

The key is the placement of the & character. It’s an indicator to sass of where you’d like to put your heirarchical selector, in this case, .btn

Leave a Reply

Your email address will not be published. Required fields are marked *