Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @apply in CSS?

Tags:

css

People also ask

Can I use @apply in CSS?

@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.

What is the use of the @apply directive?

Use @apply to inline any existing utility classes into your own custom CSS. This is useful when you need to write custom CSS (like to override the styles in a third-party library) but still want to work with your design tokens and use the same syntax you're used to using in your HTML.


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;
  };
}
  
h1 {
  @apply --header-theme;
}


h2 {
  @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 explain with this example

:root {
  --brand-color: red;/*   default value*/
  --header-theme: {
    color: var(--brand-color);
    font-family: cursive;
    font-weight: 600;
  };
}
  
h1 {
  @apply --header-theme;
}


h2 {
  --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, you can use it for far more, you can read more about mixin and variables in SASS for other ways of using it, after I suggest you read this blog post

now after I got you excited, time for the bad news, it is not implemented in browsers yet chrome, 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 re-use 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 intruction 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.