Siwicki

CSS @apply

April 28, 2016

Variable declarations and mixins are the two preprocessor components that I miss the most in projects where I have to write vanilla CSS.

CSS @applys are something that is coming starting to get support in certain browsers. @applys are away to extend or call reusable chunks of your CSS. If you have ever used sass it is very similar to calling something like a mixin.

Support for CSS @apply is horrible still. It is impossible for them to be used in the project. But, I couldn’t help but just start playing around with it in a few CodePens. The current support as listed via Chrome.

Example syntax for SASS mixins is below. You can pass mixins some variables and some other parameters as well as the ampersand which falls under one rule.

@mixin button($color) {
	border-radius: 5px;
	padding: .25em .5em;
	
	&:hover {
		cursor: pointer;
	}
}

The syntax for CSS @apply Rule is below. The syntax falls in under the :root select which, is where you would store all of your variables.

It is a clean way to contain all of your custom properties but you root declaration could start to get pretty lengthy if you have a lot of custom things at the top of the document. I like the @apply call later in the document. It feels very natural. The thing that kept tripping me up most is declaring the custom data with double —- syntax.

See the Pen CSS @apply by John Siwicki (@siwicki) on CodePen.

The code is also being used in this Codepen doesn’t not fall back into old browsers very good at all. If you loaded this in a browser that is not supported this would just not load at all.

This simple update is going to be the most exciting update toe the CSS spec. The problem is going to be the roll out of support. As you saw above from Chrome has been supporting these custom elements. Firefox and Edge have nothing at the moment for them.

I wish this was something I could use full-time. The only good polyfill that I was able to find was a postCSS plugin to allow you to use this syntax now.

The syntax is clean and tidy and fun to write and it has great support for Chrome if you are working on just an extension or an app.


John SiwickiWritten by John Siwicki who lives and works building interesting things. You should follow him on Twitter