Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm curious what the CSS directive
@apply
does. I have googled
@apply
but I couldn't find anything that could explain its meaning properly for me.
What is the usage of such a directive?
The simple way of explaining it would be; introducing variables into CSS (which is a feature of preprocessors, such as
Sass
), and mixins which are function like behaviors (also in preprocessors).
Imagine that
--header-theme
is a function (mixin):
:root {
--header-theme: {
color: red;
font-family: cursive;
font-weight: 600;
@apply --header-theme;
@apply --header-theme;
This way, you can use it in many different places without having to rewrite it again (DRY).
Now the variable part could be explained with this example:
:root {
--brand-color: red; /* Default value */
--header-theme: {
color: var(--brand-color);
font-family: cursive;
font-weight: 600;
@apply --header-theme;
--brand-color: green;
@apply --header-theme;
The mixin will have a variable sent to it and change the color.
This is not the limits of the feature, and you can use it for far more. You can read more about mixin and variables in Sass for other ways of using it, and after I suggest you read this blog post.
Now after I got you excited, it is time for the bad news. It is not implemented in browsers yet (Chrome), but it is still worth knowing that it is coming and maybe if you want to prepare yourself start with Sass.
–
–
–
–
@apply
is from a proposal that has since been abandoned, and replaced with CSS Shadow Parts.
the @apply rule, which allows an author to store a set of properties
in a named variable, then reference them in other style rules.
–
–
@apply
is pretty cool. It basically allows you to reuse CSS blocks without having to copy them around and without having to modify their selectors.
It will make it easier to use CSS frameworks and keep semantic class names at the same time.
I found this article to be a nice instruction to this feature.
Unfortunately, at the moment, browser support is basically non-existent. It can be used with a CSS pre-processor such as PostCSS.
It's future is also uncertain, if I understand well. The main advocate behind this feature stopped supporting it.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.