Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save douglas-johnson/a6831e60f8cf19a61e10d2ec7927af36 to your computer and use it in GitHub Desktop.
Save douglas-johnson/a6831e60f8cf19a61e10d2ec7927af36 to your computer and use it in GitHub Desktop.
Composing Utility Classes into Components

I would like to be able to compose utility classes into components.

PostCSS

You can do it using the PostCSS @apply plugin

:root{
	.some-utility:{
		property: value;
	}
}

.some-utility {
	@apply .some-utility;
}

.some__component--active{
	@apply .some-utility;
}

But, the originator of the @apply plugin has stopped maintaining it, and the W3C has dropped @apply from consideration.

The plugin still works of course, and packages like Tailwind CSS are still using the @apply principal. But if the idea of PostCSS is to write CSS in the real syntax, we're kidding ourselves by continuing to use dropped proposals.

SCSS

In this instance @apply is acting exactly like a mixin. So you could do the same thing in SCSS while using a supported syntax.

@mixin some-utility {
	property: value;
}

.some-utility {
	@include some-utility;
}

.some__component--active {
	@include some-utility;
}

LESS

And lastly, the simplest way to achieve this might be LESS. You can skip writing a separate mixin and class since LESS lets you make them one and the same.

.some-utility {
	property: value;
}

.some__component--active {
	.some-utility();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment